Rails3 Activerecord - Fetching All Records That Have A And B (through A Has_many Relationship)
I have the following model relationships: class Article < ActiveRecord::Base has_many :tags, :through => :article_tags end class ArticleTag < ActiveRecord::Base be
Solution 1:
I ended up solving my own problem. I constructed a named scope as follows:
scope :tagged, lambda { |tag, *tags|
tags = tags.unshift(*tag)
joins(:tags).
where("lower(tags.name) = '" + tags.uniq.collect{ |t| t.to_s.downcase }.join("' OR lower(tags.name) = '") + "'").
group("articles.id").
having("count(articles.id) = #{tags.count}")
}
So, now I can do this in my controllers:
@tagged_articles = Article.tagged('A', 'B', 'C')And @tagged_articles will include all the articles tagged with all of the tags 'A', 'B', and 'C'.
Post a Comment for "Rails3 Activerecord - Fetching All Records That Have A And B (through A Has_many Relationship)"