2010-09-12 28 views
5

我有2個模型:筆記和標籤。Rails ActiveRecord:HABTM查找參數

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()的Note類的方法。

所以,我該怎麼做:

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

我目前使用Tag.find_all_by_name(['xml','rss']).map(&:notes).flatten.uniq,但我認爲必須有一個更好的辦法

+0

怎麼樣使用行爲-AS-加標籤上的插件/寶石? – Eimantas 2010-09-12 12:10:12

+0

謝謝,我確實看到了。我想知道更多關於你如何做這種事情的機制。 – 2010-09-12 12:15:08

回答

3

到底,這就是我一直在尋找:

Note.find(:all, :include=>:tags, :conditions => ['tags.name in (?)',['rss','xml']]) 
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