我现在有这个:
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的项的查询?
例如。如果我通过"椅子"one_answers"现代"标签进行筛选,我不想要所有椅子物品和所有现代物品。我只想要所有的现代椅子。
答案就在这里:查找与所有类别(Rails3.1)匹配的产品
我需要这样做:
tags = params[:tags].split(',')
Item.joins(:tags).where(:tags => {:id => tags}).group('items.id').having("count(item_tags.tag_id) = #{tags.count}")