Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Active Record Associations

Rails • Asked by sid d
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.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 29,763+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.