Saturday 15 February 2014

ruby - Rails Scope - Get all Products where ProductCategories.size > 0 -



ruby - Rails Scope - Get all Products where ProductCategories.size > 0 -

i have simple 3 way model association product can belong multiple categories.

product has_many productcategories productcategories belongs_to product productcategories belongs_to category category has_many productcategories

i'm trying create scope returns products have visible=true , at least 1 associated productcategories.

how scope like?

here's i've tried:

scope :visible, -> { where(visible: true).where(product_categories.size > 0) }

try in product.rb:

scope :visible, -> { where(visible: true).joins(:product_categories).uniq }

it should generate sql query:

select distinct products.* products inner bring together product_categories on product_categories.product_id = products.id

or, in english: “return products have @ to the lowest degree 1 product category”. note products multiple product categories show multiple times , hence used uniq have distinct query.

ruby-on-rails ruby postgresql model scope

No comments:

Post a Comment