【问题标题】:rails 3 habtm filtering with multiple entriesrails 3 habtm 过滤多个条目
【发布时间】:2011-09-27 08:45:46
【问题描述】:

我有一个产品模型和一个产品类别模型。并且它们之间有一个habtm

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

这就是我目前所拥有的......

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

感谢您的宝贵时间!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 has-and-belongs-to-many


    【解决方案1】:

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

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

    【讨论】:

    • hm 我发现这并不能解决我的问题.. 如果我选择男士和牛仔裤.. 我不想要女士牛仔裤.. 这就是上面的代码发生的情况.. IN 就像 OR。 。 对?我需要和..我怎么能做到这一点?谢谢
    【解决方案2】:

    这是选择男装和牛仔裤而不是男装或牛仔裤的解决方案:

    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-11
      • 2012-09-23
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多