Ruby on rails Rails作用域-精确匹配的位置
是否可以在Rails中使用Ruby on rails Rails作用域-精确匹配的位置,ruby-on-rails,postgresql,ruby-on-rails-3,activerecord,Ruby On Rails,Postgresql,Ruby On Rails 3,Activerecord,是否可以在Rails中使用where in(?)query设置作用域,以检查精确匹配 例如: Post.joins(:tags).where('tags.id IN (?)', [1, 2, 3, 4]) 将找到带有标签1,2,1,2,3和1,2,3,4的帖子。但是应该只找到带有1,2,3,4标签的帖子。在子句中获得中所有匹配值的想法您必须这样做: tag_ids = [1, 2, 3, 4] Post.joins(:tags).where('tags.id IN (?)', tags_ids
where in(?)
query设置作用域,以检查精确匹配
例如:
Post.joins(:tags).where('tags.id IN (?)', [1, 2, 3, 4])
将找到带有标签
1,2
,1,2,3
和1,2,3,4
的帖子。但是应该只找到带有1,2,3,4
标签的帖子。在子句中获得中所有匹配值的想法您必须这样做:
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)
我希望这对您有所帮助。这应该在pgsql数据库中工作
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)
嗯,我不使用rails,所以您可以将帖子分组,将标记聚合到一个数组中,然后使用数组比较吗?我认为您甚至不需要在那里执行任何原始sql。我想你可以只做Post.joins(:tags).where(tags:{id:tag\u ids})
对我来说,这会返回除了[1,2,3,4]之外还有其他tag\u id的帖子。有没有办法获得精确的匹配,即只有ID为1、2和3的标签的帖子?