Adding and removing from a has_many :through relation
From the Rails associations guide, they demonstrate a many-to-many relationship using has_many :through like so:
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
How would I create and remove appointments?
- Rails 3 - Speed up Console Loading Time
- How do you use redirect_to when the action is dependent on a parameter being passed?
- RSpec Rails Login Filter
- Cannot install mysql2 in Ruby 2.0
- Rails - Show A Random Record But Not The Current
- WMD editor, rails, compass : How to get the generated Markdown code read as HTML and displayed as 'rich-text'?
If I’ve got a
@physician, do I write something like the following for creating an appointment?
@patient = @physician.patients.new params[:patient] @physician.patients << @patient @patient.save # Is this line needed?
What about code for deleting or destroying? Also, if a Patient no longer existed in the Appointment table will it get destroyed?
One Solution collect form web for “Adding and removing from a has_many :through relation”
In your code of creating an appointment, the second line is not needed, and using
#build method instead of
@patient = @physician.patients.build params[:patient] @patient.save # yes, it worked
For destroying an appointment record you could simply find it out and destroy:
@appo = @physician.appointments.find(1) @appo.destroy
If you want to destroy the appointment records along with destroying a patient, you need to add the :dependency setting to has_many:
class Patient < ActiveRecord::Base has_many :appointments has_many :physicians, :through => :appointments, :dependency => :destroy end