Reputation: 11299
I'm playing with an example from Rails Guides:
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
This example has the following setup for the models:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end
I'm trying to understand how to do the following two things:
I went through the RailsCasts 196 & 197 that deal with nested forms, but I don't see how it would apply to this situation.
Can someone provide an example or point me to a guide on this please?
Thank you
Upvotes: 2
Views: 2782
Reputation: 2167
First you have to pass the physician ID to your PatientsController#new
action. If users get there by folloing a link, this would be something like
<%= link_to 'Create an appointment', new_patient_path(:physician_id => @physician.id) %>
Or, if users have to submit a form, you can submit a hidden field with it:
<%= f.hidden_field :physician_id, @physician.id %>
Then, in PatientsController#new
:
def new
@patient = Patient.new
@physician = Physician.find(params[:physician_id])
@patient.appointments.build(:physician_id => @physician.id)
end
In new.html.erb
:
<%= form_for @patient do |f| %>
...
<%= f.fields_for :appointments do |ff |%>
<%= ff.hidden_field :physician_id %>
...
<% end %>
<% end %>
Upvotes: 3