# Has\_many :through fails on n-way join

**URL:** <https://www.ruby-forum.com/t/has-many-through-fails-on-n-way-join/155231>\
**Category:** Rails\
**Created:** [December 9, 2008, 5:50pm UTC](https://www.ruby-forum.com/t/has-many-through-fails-on-n-way-join/155231 "2008-12-09T17:50:58Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ddancer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/ecb155/32.png) [@ddancer](https://www.ruby-forum.com/u/ddancer)\
**Post date:** [December 9, 2008, 5:50pm UTC](https://www.ruby-forum.com/t/has-many-through-fails-on-n-way-join/155231/1 "2008-12-09T17:50:58Z")

</div>

I think this is a Rails bug, but I’d like to describe it here first -  
in case I’m doing something wrong.

When using an n-way (has\_many :through) join, the wrong model attr is  
selected when evaluating the join relationship.

Consider the following models. User, Group, Customer represent a  
standard HMT relationship. User, Group, Build (UGB) is an n-way style  
join - where the relationship between Users and Builds is possible  
since Builds belong to Customers who are joined to Users. Note the  
additional attributes to the HMT in the Build model (ie, :foreign\_key  
& :primary\_key).

@@@  
class User \< ActiveRecord::Base  
has\_many :groups  
has\_many :customers, :through =\> :groups  
end

class Group \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :customer  
end

class Customer \< ActiveRecord::Base  
has\_many :builds

has\_many :groups  
has\_many :members, :through =\> :groups, :source =\> :user  
end

class Build \< ActiveRecord::Base  
belongs\_to :customer

has\_many :groups, :foreign\_key =\> :customer\_id, :primary\_key  
=\> :customer\_id  
has\_many :accessors, :through =\> :groups, :source =\> :user  
end  
@@@

The problem is that the @build.accessors results in an empty [] -  
because the SQL is using the @build.id rather than  
@build.customer\_id. See related SQL listings…  
@@@  
User Load (2.6ms) SELECT \* FROM “users” WHERE (“users”.“login” =  
E’hp\_person’) LIMIT 1  
Customer Load (2.5ms) SELECT “customers”.\* FROM “customers” INNER  
JOIN groups ON customers.id = groups.customer\_id WHERE  
((“groups”.user\_id = 1046015453)) LIMIT 1  
Build Load (2.4ms) SELECT \* FROM “builds” WHERE  
(“builds”.customer\_id = 807266524)  
User Exists (11.5ms) SELECT “users”.id FROM “users” INNER JOIN  
groups ON users.id = groups.user\_id WHERE (“users”.“id” = 1046015453)  
AND ((“groups”.customer\_id = 192574979)) LIMIT 1  
@@@

@@@  
builds table:  
:id =\> 192574979;  
:customer\_id =\> 807266524;  
@@@
