Home > Blockchain >  Querying two columns with multiple conditions in ActiveRecord
Querying two columns with multiple conditions in ActiveRecord

Time:10-27

Given a Model with columns a and b, I want to get three records where a and b are a: 0 b: 3, a: 1 b: 4, and a: 2 b: 5.

The following way of retrieving records would result in issuing the query three times.

as = [0,1,2]
bs = [3,4,5]

Model.where(a: as[0], b: bs[0])
Model.where(a: as[1], b: bs[1])
Model.where(a: as[2], b: bs[2])

To make one query, I need to write the following.

Model.where(a: as[0], b: bs[0]).or(Model.where(a: as[1], b: bs[1])).or(Model.where(a: as[2], b: bs[2]))

In the above example, the number of records to be retrieved was fixed to 3. Is there any way to retrieve a group of records in a single query execution when the number of records to be retrieved is arbitrary N (the number of elements in as and bs is N)?

The way I can think of is to generate a query with a string, but I would like to achieve this with rails built-in functionality as much as possible.

CodePudding user response:

Just fold the criteria list into an AR query using #reduce, something like

criteria_list = [
  {a: 1, b: 2},
  {a: 2, b: 3},
  {a: 3, b: 4},
]

criteria_list.reduce(Model.none) do |scope, criteria|
  scope.or(Model.where(**criteria))
end

(just but be careful - the resulted query might be very inefficient, depending on the criteria set)

  • Related