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?
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With