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

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

postgresql - Rails scope - where in exact matches

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...