嵌套模型表单中的Collection_select

时间:2010-07-16 20:58:19

标签: ruby-on-rails

我有时间表模型,运行模型和运动员模型。

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

运行嵌套在Timesheets下,我想在创建时间表的同一表单上创建一些运行,如此railscast

所示
class TimesheetsController < ApplicationController
  def new
    @timesheet = Timesheet.new
    3.times { @timesheet.runs.build }
  end

在我的时间表表格中,我遇到了我的collection_select问题(运动员名称下拉,填写了运行表中的:athlete_id字段)。

<% 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字段,在Timesheet的嵌套表单中,或者我错过了什么?

1 个答案:

答案 0 :(得分:15)

看起来你没有在表单构建器上创建集合选择,尝试这样的事情:

<% f.fields_for :runs do |r| %>
  <%= r.collection_select(:athlete_id, Athlete.all(:order => 'name'), :id, :name, { :prompt => 'Select Athlete' } ) %>
<% end %>