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

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

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -