Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WHERE IN with Rails prepared statement syntax

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.

like image 653
Abraham P Avatar asked Sep 29 '13 08:09

Abraham P


Video Answer


2 Answers

I ended up using:

Item.where('id IN (?)', myArray)

like image 95
Abraham P Avatar answered Oct 21 '22 15:10

Abraham P


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.

like image 2
mcfinnigan Avatar answered Oct 21 '22 13:10

mcfinnigan