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.
Reply

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.

Reply

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.

Reply
Join the discussion
Create an account Log in

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

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

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