Nick Vanderbilt
Nick Vanderbilt

Reputation: 38440

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?

Upvotes: 0

Views: 181

Answers (2)

Mike Trpcic
Mike Trpcic

Reputation: 25659

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.

Upvotes: 2

sepp2k
sepp2k

Reputation: 370132

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.

Upvotes: 2

Related Questions