# Using :through and belongs\_to

**URL:** <https://www.ruby-forum.com/t/using-through-and-belongs-to/121587>\
**Category:** Rails\
**Created:** [November 29, 2007, 3:23am UTC](https://www.ruby-forum.com/t/using-through-and-belongs-to/121587 "2007-11-29T03:23:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mozmonkey](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/4491bb/32.png) [@Mozmonkey](https://www.ruby-forum.com/u/Mozmonkey)\
**Post date:** [November 29, 2007, 3:23am UTC](https://www.ruby-forum.com/t/using-through-and-belongs-to/121587/1 "2007-11-29T03:23:25Z")

</div>

I’m trying to reduce the mysql calls by using :include or :through and  
both methods don’t seem to work.

Here’s the breakdown: users can have friends and an avatar (image),  
so my models are setup like this:

User  
has\_many :images, :as =\> :imageable  
has\_many :friends

Image  
belongs\_to :imageable, :polymorphic =\> true

Friend  
# The user  
belongs\_to :owner\_user, :class\_name =\> “User”, :foreign\_key =\>  
“user\_id”,

```
# The friend
belongs_to :user, :class_name => "User", :foreign_key =>

```

“friend\_id”

When I list all of the User’s friends with their avatars, a MySql  
query is made for each friend image. This adds up to a lot of mysql  
requests. So my first plan was to add :include to the Friend  
association:

Friend  
# The friend  
belongs\_to :user, :class\_name =\> “User”, :foreign\_key =\>  
“friend\_id”, :include =\> :images

For some reason this did not reduce the nubmer of mysql queries, so I  
tried a :through association:

Friend  
# The friend  
belongs\_to :user, :class\_name =\> “User”, :foreign\_key =\>  
“friend\_id”

```
has_many :images, :through => :user, :limit => 1

```

Now I get the following error (most likely do to the foreign\_key in  
the belongs\_to association):

Mysql::Error: Unknown column ‘users.friend\_id’ in ‘where clause’:  
SELECT images.\* FROM images INNER JOIN users ON images.imageable\_id =  
users.id AND images.imageable\_type = ‘User’ WHERE ((users.friend\_id  
= 2)) LIMIT 1

Why is it mapping the foreign\_key incorrectly? Is it because I’m  
pointing the :through to a belongs\_to association? I would appreciate  
any solution to this issue.

Thanks,  
Jeremy

---

<div class="post-metadata">

**Author:** ![Mozmonkey](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/4491bb/32.png) [@Mozmonkey](https://www.ruby-forum.com/u/Mozmonkey)\
**Post date:** [December 2, 2007, 9:37pm UTC](https://www.ruby-forum.com/t/using-through-and-belongs-to/121587/2 "2007-12-02T21:37:47Z")

</div>

I’m actually having this exact same problem. Anyone know how to set up  
this  
polymorphic through association?
