I have 2 models: notes and tags.
class Note < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :notes
end
A tag has a name (eg. "rss", "javascript" etc.). What is the best way to retrieve all notes that have a certain list of tags? That is, I would like to have a named route like /notes/with_tags/rss,javascript
and need a class method on Note called find_with_tags()
.
So, how do I do this:
class Note
def self.find_with_tags(tags)
?????
end
end
I am currently using Tag.find_all_by_name(['xml','rss']).map(&:notes).flatten.uniq
, but I think there has to be a better way
In the end, this is what I've been searching for:
Note.find(:all, :include=>:tags, :conditions => ['tags.name in (?)',['rss','xml']])
You can also do this (though I'm not really a big fan of writing sql in queries), which will also return all notes with one of the supplied tag.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With