开发者

Collection_select within a nested model form

开发者 https://www.devze.com 2023-01-08 04:17 出处:网络
I have a Timesheet model, a Run model, and an At开发者_如何学Chlete model. class Timesheet < ActiveRecord::Base

I have a Timesheet model, a Run model, and an At开发者_如何学Chlete 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

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

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 %>

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 %>
0

精彩评论

暂无评论...
验证码 换一张
取 消