Let us say I have an array (received from the client side) of ids:
myArray = [1,5,19,27]
And I would like to return ALL items for which the (secondary) id is in that list.
In SQL this would be:
SELECT *
FROM Items
WHERE id IN (1,5,19,27)
I am aware that I could do:
Item.where(id: [1,5,9,27])
,
however the longer where query that this would be tacked onto uses the prepared statement syntax Item.where('myAttrib = ? AND myOtherAttrib <> ? AND myThirdAttrib = ?', myVal[0], myVa[1], myVal[2])
with that in mind, what I would like is the following:
Item.where('id IN ?', myArray)
However, that produces a syntax error:
ActiveRecord::StatementInvalid: PG::Error: ERROR: syntax error at or near "1"
LINE 1: SELECT "items".* FROM "items" WHERE (id in 1,2,3,4)
How can I work around this? What is the right way to use where with the prepared statement syntax for IN
expressions.
I ended up using:
Item.where('id IN (?)', myArray)
You need to change your query to the following:
Item.where('id = ?', myArray)
ActiveRecord will then convert this to an IN clause if myArray is, in fact, an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With