Dan Benjamin Dan Benjamin - 5 months ago 13
Ruby Question

Filtering results of included rails model in query

I am trying to filter out some results I get from an included model.

I have 3 classes:

Platform (has many Products, has many ProductImages through Product)
Product (has many ProductImages)
ProductImage


Now, I'm trying to get all the products and their associated images in a single query using ActiveRecord, that their images have a boolean field set to false:

platform.products.includes(:product_images).where(product_images: {dont_use: false})


The problem with the above query is that it filters out the products that don't have any product_images with dont_use:true which is not my goal.

I'm trying to get all the products with their associated images but just filter out images with dont_use: false.

Any idea on how to change my query to fit my needs?

Answer

Adding any conditions will modify the overall query defining which products are returned rather than specifying which images are included.

You could add an additional association with the condition that you need and include that. Eg:

class Product < Active record::Base
   has_many :images_in_use, -> { where(dont_use: false) }, class_name: ProductImage
end

platform.products.includes(:images_in_use)