Filter via has_many, but show all has_many objects in result

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)

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.