Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding where by using IN operator in rails3

I am trying to run a sql like below

select name from appointments where location_id in (2,3,4)

the following does not work. I am using PostgreSQL

a = [2,3,4]
Appointment.select(:name).where("location_id IN ?", a)

ActiveRecord::StatementInvalid: PGError: ERROR:  syntax error at or near "2"
LINE 1: ... FROM       "appointments"  WHERE     (location_id IN 2,3,4)
                                                                 ^
: SELECT     name FROM       "appointments"  WHERE     (location_id IN 2,3,4)
like image 510
Omnipresent Avatar asked Feb 25 '23 02:02

Omnipresent


2 Answers

You can use this:

Appointment.select(:name).where(:location_id => [2,3,4])

Hope this helps

like image 123
JCorcuera Avatar answered Mar 06 '23 05:03

JCorcuera


I don't know rails, but it looks to me like you need to do this:

Appointment.select(:name).where("location_id IN (?)", a)

i.e., put brackets around the ?.

like image 20
mpen Avatar answered Mar 06 '23 04:03

mpen