Multiple Associations, Multiple Joins


#1

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

Doing
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?

  1. 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?