All threads / Active Record Associations

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Active Record Associations

sid d asked in Rails
def partner
  has_many :centers
end

def center
 has_and_belongs_to_many :classes
 belongs_to :partner
end

def fpclass
  has_and_belongs_to_many :centers
end
  • I'd like to access all fpclasses that partner belongs to? ( Is there any other way to access except to provide another foreign key named partner_id on fpclass ) Any ideas really helpful.

You should be able to do this:

class Partner
  has_many :centers
  has_many :classes, through: :centers
end

Which Rails will know how to query based upon the other associations in the Center class. It basically compiles those associations together into the proper joins for you when you use the through option. You might have to tweak this a little bit for any class names or whatever that don't match up directly, but that should do the trick for you.

I agree with Chris. I ran into similar use cases using HABTM but ended up using has many through as an alternative. It was a much cleaner option for me.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,399+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.