Question

I would like to form the following query:

SELECT tracked_points.* 
FROM tracked_points 
WHERE
(id = 87 AND zone_id = 457)
OR
(id = 88 AND zone_id = 457)

My input to the function will be a nested array of [id, zone_id], something like:

[[87, 457], [88, 457]]

I tried a little trick I saw on the squeel gem site

arr = [[87, 457], [88, 457]]
TrackedPoint.where((["(id = ? AND zone_id = ?)"] * arr.size).join(" OR "), *arr)

but it doesn't like taking a nested array as an argument.

The solution I came up with just compiles a SQL string, but doesn't use any parameter sanitation of prepared statements:

matches = arr.map do |i|
  "(id = #{i[0]} AND zone_id = #{i[1]})"

TrackedPoint.where(matches.join(" OR ")

I have a feeling an answer is possible with squeel, but if there is a pure ActiveRecord answer I'm game to try that out as well.

  • Rails 3.2.13
  • ruby 1.9.3-p392
Was it helpful?

Solution

You have to flatten the nested array first.

TrackedPoint.where((["(id = ? AND zone_id = ?)"] * arr.size).join(" OR "), *(arr.flatten))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top