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?

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?

  • Ruby Gems or just place the source code in vendor/assets?
  • Rails-y way to query a model with a belongs_to association
  • validates_inclusion_of no longer working the same in Rails 4.1?
  • mysql2 gem installation error on centOS 6.5 deploying
  • Failed to build gem native extension ruby racer gem of different version
  • How to run Table_Print gem as stand alone gem
  • 'require': cannot load such file — 'nokogiri\nokogiri' (LoadError) when running `rails server`
  • Converting Microsoft Timezone to standards timezone data in rails
  • 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 #new:

    @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
    
    Ruby is the best programming language in the world - Ruby on Rails.