Monday, February 21, 2011

has_many at two levels

I am using Rails 2.3.5.

Company has many users. User has many emails addresses. Association tables are company_users and user_emails table.

I want to get all the email addresses for a company. What is the most efficient way to get that?

From stackoverflow
  • In the definition of Company add the line:

    has_many :emails, :through => :users
    

    Now all Company objects have an emails method, which returns all the emails of all the users of that company.

  • Try the following:

    has_many :emails, :through => :users
    

    Not sure if the association works on many-many-many, but it's worth a shot. The documentation can be found here.

0 comments:

Post a Comment