How do I keep all of the data in a has_many :through ActiveRecord relationship?

Go To StackoverFlow.com

1

I'm trying to make my ActiveRecord queries more efficient. I have Users and Items, a user has a feeling about an item, with a boolean response.

Here's my models:

User:

has_many :feelings
has_many :items, :through => :feelings

Feeling:

belongs_to :user
belongs_to :item
attr_accessible :response

Item:

attr_accessible :name

So, I can get a list of a user's feelings by:

User.find(1).feelings

and I can get a list of the items he has feelings about by:

User.find(1).items

This is all fine. What I want though, is a combination of the two above queries in one result set. Ideally, I'd like to be able to query a list of the user's items, and with those results get their response on each item.

If this was straight SQL, I could do:

SELECT * FROM items INNER JOIN feelings ON items.id=feelings.item_id WHERE feelings.user_id = 1

This then gives me everything I need in one table. This is also what ActiveRecord does when querying User.find(1).items, except it throws away the data in the feelings table before it creates my hash of results.

How do I stop it throwing out the intermediatry data, and hence saving me an extra database query?

Any help appreciated!

2012-04-03 21:22
by DaveStephens


2

You can use write it like this in Rails 3,

User.find(1).feelings.includes(:item)

and in Rails 2,

User.find(1).feelings.find(:all, :include => :item)

Usually this results two queries. One selects the feelings, and another select the items.

2012-04-04 00:08
by Yanhao
Ads