2011-07-15 103 views
0

這看起來不是那麼罕見的問題,但我找不到一個好的解決方案。一般信息:Rails 2.3:產品has_many變體 - 如何查找帶有變體條件的產品?

  • 產品,HAS_MANY變種
  • product.variants也需要,所以它們包含

當我對產品本身的條件,怎麼辦?(named_scopes的正常使用,但是這並不需要來說明問題):

Product.all(:conditions => {...}, :include => :variants) 

我無法找出什麼是隻搜索有匹配條件,變型產品的最佳方式並只包括那些。我最後的想法是:

Variant.all(:conditions => {...}, :include => :product).group_by(&:product) 

但這不是很方便,看起來不像一個好的紅寶石風格。 相反的:

@products.each do |p| 
do_stuff_with(p) 
do_other_stuff_with(p.variants) 
end 

我不得不做

@products.each do |p| 
do_stuff_with(p[0]) 
do_other_stuff_with(p[1]) 
end 

並檢查哪個變量我必須或改造的第一個,使它看起來一樣的第二個 - 凌亂...有更好的解決方案嗎?感謝您的任何建議。

回答

0

您可以將條款添加到條件和做到這一點:

Product.all(:conditions => "variants.id is not null", :include => :variants) 
+0

我的條件很複雜,我不得不使用一些更多的花樣,但是這條線索幫助了我很多!謝謝 – santuxus