2
votes

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:

  1. How do I setup the view that would create a new Patient and assign an Appointment to them with an existing Physician with an Appoint Time
  2. How do I assign an existing Patient an Appointment with a new Physician and an Appointment Time

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

1

1 Answers

3
votes

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