2010-09-12 14 views
5

Ho 2 modelli: note e tag.Rails ActiveRecord: HABTM trova i parametri

class Note < ActiveRecord::Base 
    has_and_belongs_to_many :tags 
end 

class Tag < ActiveRecord::Base 
    has_and_belongs_to_many :notes 
end 

Un tag ha un nome (ad es. "RSS", "javascript", ecc). Qual è il modo migliore per recuperare tutte le note che hanno un determinato elenco di tag? Cioè, mi piacerebbe avere un percorso chiamato come /notes/with_tags/rss,javascript e ho bisogno di un metodo di classe su Nota chiamato find_with_tags().

Allora, come faccio a fare questo:

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

Attualmente sto usando Tag.find_all_by_name(['xml','rss']).map(&:notes).flatten.uniq, ma penso che ci deve essere un modo migliore

+0

come circa usando agisce-come-oggetto di tag-on plug/gioiello? – Eimantas

+0

Grazie, l'ho visto. Mi stavo chiedendo di più sui meccanismi di come faresti qualcosa del genere. –

risposta

3

Alla fine, questo è quello che ho cercato per:

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

È anche possibile fare questo (anche se non sono davvero un grande fan della scrittura di sql nelle query), che restituirà anche tutte le note con uno dei tag forniti.

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 
Problemi correlati