匹配查询中所有活动记录中的关系 [英] match all in active record relations in a query

查看:81
本文介绍了匹配查询中所有活动记录中的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个activerecord查询来匹配params数组中的所有项目。

I need an activerecord query to Match ALL items in a params array.

让用户说has_many角色。并且每个角色都有一个名字。

lets say user has_many roles. and each role has a name.

当我通过[演员,制片人,歌手]时。我希望查询返回给我具有所有这三个角色或更多角色的用户。

when i pass ['actor', 'producer', 'singer']. I expect the query to return me the users with all the those three roles or more.

但是我下面的方法实现将返回具有至少一个与通过的数组中的角色名称匹配的角色名称的用户

But my method implementation below would return users with having atleast one role name matching to those in the array passed

我当前的方法基于找到任何标签而不是全部匹配来给出结果

My current method gives results based on finding any of the tags, not "MATCH ALL"

class User < ActiveRecord::Base
    has_many :roles

    def self.filter_by_roles(roles)
        User.joins(:roles).includes(:roles).where(:roles => {:name => roles})
    end
end

请帮我解决这个问题。

Please help me with a solution for this.

查询后,我不想执行任何数组操作,以检查返回的结果对象是否包含所有角色。这是因为我需要从中返回活动记录关系对象。

I don't wanna do any array operations after the query checking if the returned result objects contain all the roles or not. This is because I need the Active Record Relation object to be returned from this.

预先感谢。

推荐答案

尝试一下。

User.joins(:roles).includes(:roles).where(:roles => {:name => roles}).group('usermail').having("COUNT(DISTINCt role_id) = 3")

假定该字段 usermail 用于标识用户。

assuming that field usermail is using to identify users.

这篇关于匹配查询中所有活动记录中的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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