开发者

How to construct an exclusive IN query using Ruby and ActiveRecord?

UPDATED/EDITED to clarify:

I have the following defined in my Blog AR object

  scope :with_tag_tokens, lambda {|name_tokens| 
    joins(:tags).where(:tags => {:name_token => name_tokens}) unless name_tokens.empty?
  }

Whereas the following query would return all Blogs with Tags that have a "name_token" attribu开发者_高级运维te equal to 1 OR 3 OR 5 (If I passed in [1,3,5] of course) ... I want to know if there is a way to construct a similar query that would only return Blogs that are only associated to Tags with the "name_tokens" of 1 AND 3 AND 5.

In other words ... I only want to return Blog A if it is associated to Tag 1 and Tag 3 and Tag 4.

Thanks -wg


Whether or not this is an efficient way of handling this ... it works

tags = ['rails', 'ruby']
BlogEntry.joins(:tags).where(:tags => {:name_token => tags}).group(BlogEntry.column_names.map {|c| BlogEntry.table_name + "." + c }.join(',')).having("count(#{BlogEntry.table_name + '.id'}) =#{tags.count}")

What do ya'll think? Is there a better way? Perhaps going straight-up sql is the proper approach here ... if so, I'm definitely interested in hearing back from others good or bad.

* UPDATE * Here is what the sql looks like in case folks are interested:

SELECT \"blog_entries\".* 
FROM \"blog_entries\" 
     INNER JOIN \"blog_entries_tags\" ON \"blog_entries_tags\".\"blog_entry_id\" = \"blog_entries\".\"id\" 
     INNER JOIN \"tags\" ON \"tags\".\"id\" = \"blog_entries_tags\".\"tag_id\" 
WHERE \"tags\".\"name_token\" IN ('grace', 'gratitude') 
GROUP BY id 
HAVING count(blog_entries.id) =2 
ORDER BY published_at DESC, title, created_at DESC

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜