0
class List < AR::Base
  has_many :items
end

class Item < AR::Base
  belongs_to :list
  att_accessible :tag
end

我想要一个只返回列表的方法,其中包含传递给该方法的所有标签。

IEfiltered_lists = List.filter_by_item_tags(['tag1', 'tag2'])

我当前的实现返回一个列表,tag1或者tag2我希望它只返回同时包含 tag1和的列表tag2

到目前为止我所拥有的:

class List < AR::Base
  def self.filter_by_item_tags(tags)
    items = Item.includes(:lists)
    items.find_all_by_tag(tags).map(&:lists).flatten
  end
end
4

1 回答 1

2

我认为joins有条件可能会有所帮助。你可以试试这样的(我没有测试过)

def self.filter_by_item_tags(tags)
  # Get items with the given tag, and check that all tags have been found
  List.joins(:items).where("items.tag in (?) and count(distinct items.tag) = ?", tags, tags.length)
end

或者

List.joins(:items).select('count(distinct items.tag) as tags_count').where(:items => { :tag => tags }).group('tags_count').having('tags_count = ?', tags.length)
于 2012-12-03T10:52:22.160 回答