嵌套模型表单中的 Collection_select [英] Collection_select within a nested model form
问题描述
我有一个时间表模型、一个跑步模型和一个运动员模型.
I have a Timesheet model, a Run model, and an Athlete model.
class Timesheet < ActiveRecord::Base
has_many :runs, :dependent => :destroy
accepts_nested_attributes_for :runs
end
class Run < ActiveRecord::Base
belongs_to :timesheet
belongs_to :athlete
end
class Athlete < ActiveRecord::Base
has_many :runs
end
运行嵌套在时间表下,我想在创建时间表的同一表单上创建一些运行,如下所示 railscast
Runs are nested under Timesheets, and I want to create a few runs on the same form I create a Timesheet, as shown in this railscast
class TimesheetsController < ApplicationController
def new
@timesheet = Timesheet.new
3.times { @timesheet.runs.build }
end
在我的时间表表单中,我的 collection_select(运动员姓名下拉列表填充 Runs 表中的 :athlete_id 字段)出现问题.
On my Timesheet form, I'm experiencing a problem with my collection_select (a drop down of Athlete names which populates the :athlete_id field in the Runs table).
<% form_for(@timesheet) do |f| %>
<%= f.error_messages %>
<%= f.label "Date" %>
<%= f.text_field :date %>
<% f.fields_for :runs do |builder| %>
<%= collection_select(:run, :athlete_id, Athlete.all(:order => 'name'), :id, :name, { :prompt => 'Select Athlete' } ) %>
<% end %>
<%= f.submit 'Create' %>
<% end %>
是否可以在时间表的嵌套表单中使用如上所示的 collection_select 填充 Run 的 :athlete_id 字段,还是我遗漏了什么?
Is it possible to populate the :athlete_id field of a Run with a collection_select as shown above, within a nested form for Timesheet, or am I missing something?
推荐答案
您似乎没有在表单生成器上创建集合选择,请尝试以下操作:
It looks like you're not creating the collection select on the form builder, try something like this:
<% f.fields_for :runs do |r| %>
<%= r.collection_select(:athlete_id, Athlete.all(:order => 'name'), :id, :name, { :prompt => 'Select Athlete' } ) %>
<% end %>
这篇关于嵌套模型表单中的 Collection_select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!