# Duplicate joins with eager loading + include?

**URL:** <https://www.ruby-forum.com/t/duplicate-joins-with-eager-loading-include/181629>\
**Category:** Rails\
**Created:** [January 14, 2010, 11:51pm UTC](https://www.ruby-forum.com/t/duplicate-joins-with-eager-loading-include/181629 "2010-01-14T23:51:59Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 14, 2010, 11:51pm UTC](https://www.ruby-forum.com/t/duplicate-joins-with-eager-loading-include/181629/1 "2010-01-14T23:51:59Z")

</div>

I am working on a centralized authorization framework. I have models  
for: App, Permission, and Role.

In app.rb:

has\_many :admins, :through =\> :permissions,  
:source =\> :user, :include =\> :roles,  
:conditions =\> [‘roles.app\_admin = ?’, true]

The above defines which users are administrators for apps, via the  
boolean that’s part of a Role under the App.

This works fine standalone, by just obtaining @app.admins.

What is broken is when I do something like:

App.find(54).admins.include?(User.find\_by\_login(‘jdoe’))

I get:

ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column  
name: permissions.user\_id: SELECT DISTINCT “users”.id FROM “users” LEFT  
OUTER JOIN “permissions” ON (“users”.“id” = “permissions”.“user\_id”)  
LEFT OUTER JOIN “roles” ON (“roles”.“id” = “permissions”.“role\_id”)  
INNER JOIN “permissions” ON “users”.id = “permissions”.user\_id WHERE  
(“users”.“id” = 1399) AND ((“permissions”.app\_id = 54) AND  
((roles.app\_admin = ‘t’))) LIMIT 1

Rails is joining users.id to permissions.id twice and SQL thus barfs.  
Can anyone help me determine why? It seems to be something related to  
running include? along with this specific type of model relationship. I  
know I can workaround it with the collect method or such but the SQL is  
not nearly as efficient.

Thank you!
