In my latest project I needed to fetch a group of tasks who where linked to a group of categories. All that I have are the Id’s of te categories which made me write the following code
Tasks.find(:all,
:conditions => ["categorie_id IN (?)", @categories.join(',')])
It seemed to work, but apparently I didn’t test it right and my tests where not sufficient enough.
This code produces the following SQL:
SELECT * FROM `tasks` WHERE (categorie_id IN ('1,2,3,4'))
This is obviously wrong. You’ll get quotes around the row of id’s which is kind of logical if you think about it. Afteral it’s a string. To prevent this from happening, simply apply the following syntax
Tasks.find(:all,
:conditions => ["categorie_id IN (#{@categories.join(',')})"])
ActiveRecord find and MySql ‘IN’ gotcha
In my latest project I needed to fetch a group of tasks who where linked to a group of categories. All that I have are the Id’s of te categories which made me write the following code
It seemed to work, but apparently I didn’t test it right and my tests where not sufficient enough.
This code produces the following SQL:
This is obviously wrong. You’ll get quotes around the row of id’s which is kind of logical if you think about it. Afteral it’s a string. To prevent this from happening, simply apply the following syntax