Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 274
jktress Avatar asked Jul 16 '10 20:07

jktress


1 Answers

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 %>
like image 131
Winfield Avatar answered Nov 16 '22 05:11

Winfield