簡體   English   中英

如何在Rails ActiveRecord中獨家過濾相關模型中的標簽

[英]How can I filter tags in a related model exclusively in Rails ActiveRecord

我目前有這個:

class Item < ActiveRecord::Base
  has_many :item_tags, :dependent => :delete_all
  has_many :tags, :through => :item_tags, :order => 'name ASC'

  scope :asc, order('filename ASC')
end

class Tag < ActiveRecord::Base
  has_many :item_tags, :dependent => :delete_all
  has_many :items, :through => :item_tags

  scope :asc, order('name ASC')

  validates_presence_of :name
  validates_uniqueness_of :name
end

class ItemTag < ActiveRecord::Base
  belongs_to :item
  belongs_to :tag

  scope :asc, order('position ASC')
end

我可以使用以下標記輕松地進行包含性過濾:

@items = Item.asc
@items = @items.joins(:item_tags).where('item_tags.tag_id' => params[:tags]) if params[:tags]
# params[:tags] contains a string of comma separated tags IDs like: "13,14,15"

但是結果(當然)包括所有帶有標簽13、14或15的商品。

如何建立僅返回標簽為13 AND 14 AND 15的商品的查詢?

例如。 如果我按“椅子”和“現代”標簽過濾,則不需要所有椅子物品和所有現代物品。 我只想要所有現代椅子項目。

答案在這里: 查找與所有類別匹配的產品(Rails 3.1)

我需要這樣做:

tags = params[:tags].split(',')
Item.joins(:tags).where(:tags => {:id => tags}).group('items.id').having("count(item_tags.tag_id) = #{tags.count}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM