match all in active record relations in a query

activerecord, associations, ruby-on-rails, ruby-on-rails-3, sql

Solution

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.

Problem

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.

Original source