Rails ActiveRecord:HABTM查找参数

时间:2010-09-12 12:08:04

标签: ruby-on-rails activerecord

我有2个型号:笔记和标签。

class Note < ActiveRecord::Base
  has_and_belongs_to_many :tags
end

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :notes
end

标签有一个名称(例如“rss”,“javascript”等)。检索具有特定标记列表的所有注释的最佳方法是什么?也就是说,我希望有一个像/notes/with_tags/rss,javascript这样的命名路由,并且需要一个名为find_with_tags()的注释类方法。

那么,我该怎么做:

class Note
  def self.find_with_tags(tags)
    ?????
  end
end

我目前正在使用Tag.find_all_by_name(['xml','rss']).map(&:notes).flatten.uniq,但我认为必须有更好的方法

2 个答案:

答案 0 :(得分:3)

最后,这就是我一直在寻找的东西:

Note.find(:all, :include=>:tags, :conditions => ['tags.name in (?)',['rss','xml']])

答案 1 :(得分:1)

你也可以这样做(虽然我不是在查询中编写sql的忠实粉丝),它也会返回所有提供标签的笔记。

class Note < ActiveRecord::Base
  has_many :notes_tags
  has_many :tags, :through => :notes_tags

  def self.find_with_tags(*tags)
    all(:joins => :notes_tags, :conditions => ["notes_tags.tag_id in (select id from tags where name in (?))", tags], :group => 'notes.id')
  end

end