Hi student,
First, I'm glad to hear you're making progress learning Rails ActiveRecord
associations. Second, before you consider yourself stuck, I would always recommend seeking out code documentation. Most good modern software has helpful documentation that should be able to steer you in the right direction. The Rails documentation has a great example on has_many :through
associations. Let's use their example.
has_many
tells ActiveRecord
that we want each instance of this model to have associations to one or more instances of another model. Now imagine we want to simply access data of a third model that is referenced only by association of our referenced model from our first model (sorry that was a mouthful). This is where :through
comes into play. Consider the following:
class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
end
So now an instance of a Physician
has access to patients
because of its association through Appointments
.
# Get the last name of this physician's first patient
first_patient_last_name = physician.patients.first.last_name
I hope this helps. Please let me know if you need further help! Good luck!