Rails 2.3: Product has_many Variants - how to do find on Product with conditions on Variant?
This looks like not so rare problem, but yet I couldn't find a good solution. General info:
- Product that has_many Variants
- product.variants are also needed, so they are included
When I have conditions on the Product itself, I do (named_scopes are used normally, but this is not needed to illustrate the problem):
Product.all(:conditions => {...}, :include => :variants)
I cannot find out what's the best way to search only for Products that have variants which match conditions and include only those. My last idea was:
Variant.all(:conditions => {...}, :include => :product).group_by(&:product)
But this is not very convenient and does not look like a nice ruby style. Instead of:
@products.each do |p|
do_stuff_with(p)
do_other_stuff_with(p.variants)
end
I'd have to do
@products.each do |p|
do_stuff_with(p[0])
do_other_stuff_with开发者_开发百科(p[1])
end
And check which variable do I have or transform the first one to make it look the same as the second - messy... Is there a better solution? Thanks for any suggestions.
You can add a clause to conditions and do this:
Product.all(:conditions => "variants.id is not null", :include => :variants)
精彩评论