Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activerecord return objects that match ALL attributes in array

Right now I have this query:

@events = Event.joins(:packages).where("packages.kind IN (?)", packages).distinct

And it returns objects that match just a single attribute in the packages array.

I would like ActiveRecord to only return objects that match all attributes in the given array. How would that be done with my query set up the way it is?

like image 266
Antonio Avatar asked Oct 19 '25 12:10

Antonio


2 Answers

I feel like there must be a simpler way of doing this. But, in Postgres, try:

Event.joins(:packages).having('array_agg(packages.type) @> array[?]', packages).group(:id)


like image 115
chrismanderson Avatar answered Oct 21 '25 02:10

chrismanderson


You can construct a query with multiple conditions

@events = Event.joins(:packages).distinct
packages.each do |package|
  @events = @events.where("packages.kind = ?", package)
end

@events
like image 43
Alex Kojin Avatar answered Oct 21 '25 02:10

Alex Kojin