rails: Get a list of items tagged x AND y AND z

Posted by egarcia on Stack Overflow See other posts from Stack Overflow or by egarcia
Published on 2010-06-15T14:39:09Z Indexed on 2010/06/15 14:42 UTC
Read the original article Hit count: 156

Filed under:
|
|
|

I've got two models: item and tags. Both have a name attribute. I want to find items tagged with several tags.

class Item < ActiveRecord::Base
  has_many :tags
  validates_presence_of :name
end

class Tag < ActiveRecord::Base
  belongs_to :item
  validates_presence_of :name
end

Given a list of tag ids, I can easily enough get the list of items tagged with one tag or the other:

# Find the items tagged with one or more of the tags on tag_ids
Item.all(:conditions => ['tags.id in (?)', tag_ids], :joins => :tags)

If tag_ids is {1,4}, then I get all pictures tagged with 1, or 4, or both.

I want to know now how to get the pictures that are tagged with both - 1 AND 4.

I can't even imagine the SQL that is needed here.

© Stack Overflow or respective owner

Related posts about sql

Related posts about ruby-on-rails