Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord: HABTM find parameters

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

like image 669
Flavius Stef Avatar asked Oct 14 '22 00:10

Flavius Stef


2 Answers

In the end, this is what I've been searching for:

Note.find(:all, :include=>:tags, :conditions => ['tags.name in (?)',['rss','xml']])
like image 144
Flavius Stef Avatar answered Oct 29 '22 03:10

Flavius Stef


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
like image 30
hellvinz Avatar answered Oct 29 '22 02:10

hellvinz