Forum: Ruby on Rails Filter via has_many, but show all has_many objects in result

F40475229930a4bbc95e9d73a0bf6536?d=identicon&s=25 unknown (Guest)
on 2013-03-07 23:23
(Received via mailing list)
I have a model, resource, which has_many categories:

    has_many :category_resources, :dependent => :destroy
    has_many :categories, :through => :category_resources

I have it setup to filter on categories, for a list view:
records =
Resource.includes(:categories).where("category_resources.category_id" =>
categories)

But I want it to still show all categories  for a particular resource
the
listing, rather than just what was searched on.

eg, a resource, apple, has the categories, Food, Fruit, and Red.

If you select the resource Food, it should show:
Name: Apple
Categories: [Food, Fruit, Red]

Instead, I'm just getting:
Name: Apple
Categories: [Food]

What would be the best way to structure my query for this to work?
5f94b9b346c2aa648a80bc259978e5bc?d=identicon&s=25 Colin Law (Guest)
on 2013-03-08 10:01
(Received via mailing list)
On 7 March 2013 21:34,  <dcecuweb@gmail.com> wrote:
> I have a model, resource, which has_many categories:
>
>     has_many :category_resources, :dependent => :destroy
>     has_many :categories, :through => :category_resources
>
> I have it setup to filter on categories, for a list view:
> records =
> Resource.includes(:categories).where("category_resources.category_id" =>
> categories)

Can you explain in words what you are trying to achieve with the query
above please.

> Instead, I'm just getting:
> Name: Apple
> Categories: [Food]

If you have a Resource in resource, then resource.categories should
always show you all the categories.

Colin
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2013-03-08 12:48
(Received via mailing list)
On Thursday, March 7, 2013 9:34:17 PM UTC, dcec...@gmail.com wrote:
>
>
This use of includes combined with the condition makes rails use a join
to
do the include, but, as you've found the filtering then filters the
included rows, since everything is done with a single query. I'd try
something like

    Resource.joins(:category_resources).where("category_resources.category_id"
=> categories).preload(:categories)

assuming that you want the proloading for performance reasons. This
splits
out the eager loading stuff from the main query.

Fred
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.