Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match all in active record relations in a query

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

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

I don't want to 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.

Thanks in advance.

like image 535
aBadAssCowboy Avatar asked Oct 23 '25 19:10

aBadAssCowboy


1 Answers

Try this.

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

assuming that field usermail is using to identify users.

like image 126
Thaha kp Avatar answered Oct 26 '25 09:10

Thaha kp