Skip to content

Instantly share code, notes, and snippets.

@astout
Created October 7, 2018 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astout/c916f55aa08f061fa337bb76837623ee to your computer and use it in GitHub Desktop.
Save astout/c916f55aa08f061fa337bb76837623ee to your computer and use it in GitHub Desktop.
Thinkful Rails Response

Rails

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment