Forum: Ruby on Rails Multiple Associations, Multiple Joins

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
6f5a03d94ccceec5a40460018c26bf1b?d=identicon&s=25 Sean Hermany (seanh)
on 2006-03-17 16:12
Two separate questions in this post.

1. I have a model with two foreign keys to the same table. In this case,
the associations represent "categories", so I have category1_id and

belongs_to :category, :foreign_key => "category1_id"

works, and I can use foo.category, however when I want to access the
second category, I am forced to use SQL. I realize that with a many-many
relationship like this, a bridging table might have been appropriate,
however I know that I will always have two categories per record and no
more, so the complication didn't seem worth it.

I feel like things like this may come up a lot, for instance if a flight
model had  a pilot and co-pilot foreign key, both referencing an
employee table, or similar. Is there a way to make this work so that I
can access each category with the same ease?

2. I have not been able to get two natural joins to work in the same
query. That is, say I have 3 models, for instance, office with a foreign
key of building_id, building with a foreign key of employee_id (the
building manager), and employee.

I cannot get any combination of :include in either associations or find
method calls to work so that I can iterate over all offices and do
office.building.employee without it needing to do a separate sql query
for each employee?
This topic is locked and can not be replied to.