代码之家  ›  专栏  ›  技术社区  ›  Flavius Stef

Rails ActiveRecord:HabTM查找参数

  •  5
  • Flavius Stef  · 技术社区  · 14 年前

    我有两个模型:注释和标签。

    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 回复  |  直到 14 年前
        1
  •  3
  •   Flavius Stef    14 年前

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

    Note.find(:all, :include=>:tags, :conditions => ['tags.name in (?)',['rss','xml']])
    
        2
  •  1
  •   hellvinz    14 年前

    您也可以这样做(尽管我不太喜欢在查询中编写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