【问题标题】:Find all Products that contain specific multiple Tags查找包含特定多个标签的所有产品
【发布时间】:2018-03-12 16:46:33
【问题描述】:

我想查找只有一组特定标签的产品。

例如:具有两个或多个 id 的数组:[1, 2] 并且只返回具有这两个标签的产品。

我使用过Product.includes(:tags).where('tags.id' => [64, 65]).all,但这会返回包含其中一个这些标签的任何产品。

这是我的模型:

# models/product.rb
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings

# models/tag.rb
has_many :taggings
has_many :products, through: :taggings

# models/tagging.rb
belongs_to :product
belongs_to :tag

【问题讨论】:

    标签: ruby-on-rails associations rails-activerecord


    【解决方案1】:

    如果你有tag_ids = [64, 65],或许可以这样做:

    tag_ids.each_with_object(Product.includes(:tags)) do |tag_id, query_base|
      query_base.where('tags.id' => tag_id)
    end
    

    我相信应该and 你的wheres 并给你products 具有所有指定的tags。

    【讨论】:

    • 谢谢,不幸的是,这似乎仍然返回相同的东西。 ://
    • 它返回一个ActiveRecord_Relation,其中包括Products,其中tag 和id either 64 or @987654332 @?嗯……
    猜你喜欢
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多