Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to make scope in Rails with where IN (?) query, which will check exact matches?

for example:

Post.joins(:tags).where('tags.id IN (?)', [1, 2, 3, 4])

will find posts with tags 1, 2, 1, 2, 3 and 1, 2, 3, 4. But should find only post with 1, 2, 3, 4 tags.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

The idea to get matching all values in IN clause you have to do this:

tag_ids = [1, 2, 3, 4]
Post.joins(:tags).where('tags.id IN (?)', tags_ids).group("posts.id")
                    .having("COUNT(posts.id) >= ?", tag_ids.length)

I hope this help you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...