With rails, how do I find objects NOT in a Has Many Through collection? -


let's article has many tags through taggings.

article    has_many :taggings    has_many :tags, :though :taggings end 

@article.tags #gives tags article

how find tags article not have?

thanks

the way can think of using rails finders 2 queries , subtract:

class article   def unused_tags     tag.all - self.tags   end end 

alternately, through sql (which more efficient since you'd getting rows want):

query = <<-eos select * tags t not exists (   select 1   taggings   article_id = ?     , tag_id = t.id ) eos tag.find_by_sql [query, article.id] 

Comments

Popular posts from this blog

ruby - When to use an ORM (Sequel, Datamapper, AR, etc.) vs. pure SQL for querying -

php - PHPDoc: @return void necessary? -

c++ - Convert big endian to little endian when reading from a binary file -