我正在用两个模型做一个简单的练习。运动和团队,定义为
rails g scaffold sport name:integer rails g scaffold team name:integer fans:integer sport:references
(Note: The reason I'm using scaffold is rapidly prototyping so I can learn/experiment with the parts I'm not familiar with yet)
Problem is that my "sport" (i.e. the foreign key reference) is showing like the following
So it's got that weird #<blahl blah>
notation to it...
<%= form_for(@team) do |f| %>
<% if @team.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@team.errors.count, "error") %> prohibited this team from being saved:</h2>
<ul>
<% @team.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :fans %><br />
<%= f.number_field :fans %>
</div>
<div class="field">
<%= f.label :sport %><br />
<%= f.text_field :sport %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我试过将一行更改为 @team.sport.name
但它会导致错误 undefined method 'Ice Hockey' for #<Team:0x3e7e040>
...关于如何从此处正确显示名称的任何想法?
最佳答案
您正在使用 text_field
来引用现有对象,将 Sports 作为选项的 select
在这里更合适。
这是必须更改的地方:
<div class="field">
<%= f.label :sport %><br />
<%= f.text_field :sport %>
</div>
收件人:
<div class="field">
<%= f.label :sport %><br />
<%= f.select :sport_id, options_for_select(Sport.all.map{|s|[s.name, s.id]}) %>
</div>
f.select
将在 HTML 中生成一个选择框,选项将包含您数据库中的所有运动。
一些关于它的文档:
- http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
- http://guides.rubyonrails.org/form_helpers.html#select-boxes-for-dealing-with-models
更简洁的方法 是在您的 Controller 中设置一个变量 @sports
然后在您的 View 中调用它:
# in controller
def edit
@sports = Sport.scoped
#...
# in edit view
<div class="field">
<%= f.label :sport %><br />
<%= f.select :sport_id, options_for_select(@sports.map{ |s| [s.name, s.id] }) %>
</div>
附加信息:如果您想为选择“预选”一个选项,您必须将它作为 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]
关于ruby-on-rails - Rails - 在表单中显示外键引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16848702/