Rails 2.3:产品有_许多变体 - 如何在变体条件下查找产品?

发布于 2024-11-19 23:14:00 字数 749 浏览 2 评论 0原文

这看起来并不是那么罕见的问题,但我却找不到一个好的解决方案。一般信息:

  • 具有多个变体的产品
  • 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稀香 2024-11-26 23:14:00

您可以向条件添加一个子句并执行以下操作:

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

You can add a clause to conditions and do this:

Product.all(:conditions => "variants.id is not null", :include => :variants)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文