Kashiftufail
Kashiftufail

Reputation: 10885

SQL error in ActiveRecord

Hi i am using rails and active record and there is some problem with my active record query.

session[:profile_ids] = [2,4,5]  
@profiles = UserProfile.where("key = ? and id in (?)", 'Noc_Address',
     session[:profile_ids])

But i receive this error:

Mysql::Error: You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax to use near 
'key = 'Noc_Address')' at line 1: SELECT `user_profiles`.* FROM 
`user_profiles`  WHERE (id in (361) and key = 'Noc_Address')

How i can correct it?

Thanks.

Upvotes: 0

Views: 220

Answers (1)

Stefan
Stefan

Reputation: 114138

KEY is a reserved word so you have to escape it:

@profiles = UserProfile.where("`key` = ? and id in (?)", 'Noc_Address', session[:profile_ids])

Or let Rails handle this for you:

@profiles = UserProfile.where(key: 'Noc_Address', id: session[:profile_ids])

Upvotes: 4

Related Questions