Rails范围-完全匹配的地方 [英] Rails scope - where in exact matches

查看:74
本文介绍了Rails范围-完全匹配的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用在IN(?)查询中在Rails中进行范围设置,以检查精确匹配?

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

例如:

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

将找到带有标签的帖子1、2 1、2、3 1、2、3、4 。但是应该只查找带有 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.

推荐答案

要匹配 IN 子句中所有值的想法,您必须执行以下操作:

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)

希望对您有所帮助。

这篇关于Rails范围-完全匹配的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆