Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 718
Pavel Babin Avatar asked Dec 28 '25 23:12

Pavel Babin


2 Answers

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.

like image 82
akbarbin Avatar answered Dec 30 '25 16:12

akbarbin


This should be worked in pgsql database..

opp_id = Post.joins(:post_tags).group('post.id').having('ARRAY[?] = ARRAY_AGG(post_tags.tag_id ORDER BY post_tags.tag_id)', tags.sort).pluck(:id)
like image 21
muhammad zaman Avatar answered Dec 30 '25 15:12

muhammad zaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!