私は現在これを持っています:
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 と 14 と 15 を持つアイテムのみを返すクエリを作成するにはどうすればよいですか?
例えば。「chair」と「modern」タグでフィルタリングしている場合、すべての椅子のアイテムとすべてのモダンなアイテムは必要ありません。モダンな椅子のアイテムがすべて欲しいだけです。