Rails 2.3:产品有_许多变体 - 如何在变体条件下查找产品?
这看起来并不是那么罕见的问题,但我却找不到一个好的解决方案。一般信息:
- 具有多个变体的产品
- 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
并检查我有哪个变量或转换第一个变量以使其看起来与第二个相同 - 混乱......有更好的解决方案吗?感谢您的任何建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以向条件添加一个子句并执行以下操作:
You can add a clause to conditions and do this: