Antonio
Antonio

Reputation: 751

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?

Upvotes: 4

Views: 1060

Answers (2)

chrismanderson
chrismanderson

Reputation: 4813

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)


Upvotes: 2

Alex Kojin
Alex Kojin

Reputation: 5204

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

Upvotes: 1

Related Questions