I have a Rails4 app, running postgres, and I need to query on Products where its IN ANY category (passing in array of categories) and where it matches ALL tags (passing in array of tags).
Here would be an example passing in category ids, and tag names arrays.
Product.with_categories_and_tags( [12,15,17], ["plastic","white"] )
class Product
scope :with_categories_and_tags, -> (category_ids, tag_array) {
joins(:tags, :categories)
.select("DISTINCT ON (products.id) products.*, count(*) AS count")
.where(tags: { slug: tag_array })
.where(categories:{id:category_ids})
.group('products.id')
.having("count(*) = #{tag_array.size}")
}
end
That's what I came up with, but its not giving me Products that "Match All" tags in the array.
I am thinking it has something to do with my count(*) as its running through all categories as well as all tags, so the count would be off, am I right? What is the proper way to count only on the associated tags?
Aucun commentaire:
Enregistrer un commentaire