Rails – 在表单中显示外键引用

我正在做两个模型的简单练习。 体育和团队,定义为

 rails g脚手架运动名称:整数
 rails g scaffold团队名称:整数粉丝:整数运动:参考

(注意:我使用脚手架的原因是快速原型设计,所以我可以学习/试验我不熟悉的部件)

问题是我的“运动”(即外键参考)显示如下 在此处输入图像描述

所以它有奇怪的#符号……

   

prohibited this team from being saved:




我已经尝试将一行更改为@team.sport.name但是它导致错误undefined method 'Ice Hockey' for # …任何想法如何从这里正确显示名称?

您正在使用text_field来引用现有对象,使用Sports作为选项的选择在这里更合适。

这是必须改变的地方:

 
<%= f.label :sport %>
<%= f.text_field :sport %>

至:

 
<%= f.label :sport %>
<%= f.select :sport_id, options_for_select(Sport.all.map{|s|[s.name, s.id]}) %>

f.select将生成一个HTML格式的选择框,选项将是我数据库中的所有体育项目。

一些关于它的文档

@sports在控制器中设置变量@sports ,然后在视图中调用它:

 # in controller def edit @sports = Sport.scoped #... # in edit view 
<%= f.label :sport %>
<%= f.select :sport_id, options_for_select(@sports.map{ |s| [s.name, s.id] }) %>

附加信息:如果要“预先选择”选项的选项,则必须将其作为options_for_select帮助程序的第二个参数传递:

 options_for_select(@sports.map{ |s| [s.name, s.id] }, params[:sport_id]) # this will select by default the option that matches the value of params[:sport_id]