Rails/SQL: Find which belongs to all, not any -
for example, i'v got simple app post model , tag model. associated each other has-many. need find posts, associated number of tags. example, want find posts, tagged "cat" , "forest" tags, not tagged "forest" or "cat". so, cat's in forest.
how can run such query in rails or in raw sql? if use in operator on associated model, like
posttag.where(tag_id: [1,2])
i post's of 2 tags, need intersection. how can that?
well 1 stab following:
post_tag_ids = posttag.joins(:tags).where('tags.id = 1').pluck(:id) & posttag.joins(:tags).where('tags.id = 2').pluck(:id) post_tags = posttag.find(post_tag_ids)
or better yet
(posttag.joins(:tags).where('tags.id = 1') & posttag.joins(:tags).where('tags.id = 2')).uniq
so first finding post_tag ids of post tag 1 tag 2, getting intersection of 2 sets, , querying those.
most of time, people try accomplish task 1 liner in rails, when simplest way might right under noses. result in 3 queries however, keep in mind. if in sql, same thing using subqueries however.
Comments
Post a Comment