Rails 3 habtm 具有多个条目的过滤

发布于 2024-12-06 20:07:45 字数 337 浏览 2 评论 0原文

我有一个产品模型和一个产品类别模型。它们之间有一个习惯

我有“男士”和“牛仔裤”等类别,我想过滤这些类别。对男士进行过滤是没有问题的,但我需要过滤多个参数(男士和牛仔裤)。我尝试了一些变化,但我坚持这个。

这就是我到目前为止所拥有的..

Product.joins(:product_categories).where(['product_categories.id = 5 and product_categories.id = 6'])

感谢您的时间!

i have a product model and a product category model. and theres a habtm between those.

i have categories like 'men' and 'jeans' and i would like to filter these. to do a filter on men is no problem but i need to filter multiple parameters (men and jeans). i tried some variations but i'm stuck on this.

this is what i have so far..

Product.joins(:product_categories).where(['product_categories.id = 5 and product_categories.id = 6'])

thanks for your time!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

独木成林 2024-12-13 20:07:45

像这样编写并传递您要过滤的 id 数组怎么样?

Product.joins(:product_categories).where(['product_categories.id in (?)', _product_categories_ids ])

How about writting it like this and passing array of ids you're looking to filter by?

Product.joins(:product_categories).where(['product_categories.id in (?)', _product_categories_ids ])
冷心人i 2024-12-13 20:07:45

这是选择 men AND jeans 而不是 men OR jeans 的解决方案:

@products = Product.scoped

@product_category_ids.each.with_index do |product_category_id, index|
  @products = @products.joins("INNER JOIN product_categories_products pcp#{index} ON pcp#{index}.product_id = products.id AND pcp#{index}.product_category_id = #{product_category_id}")
end

this is the solution which selects men AND jeans and not men OR jeans:

@products = Product.scoped

@product_category_ids.each.with_index do |product_category_id, index|
  @products = @products.joins("INNER JOIN product_categories_products pcp#{index} ON pcp#{index}.product_id = products.id AND pcp#{index}.product_category_id = #{product_category_id}")
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文