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

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(',')})"])
Posted in Coding, Ruby on Rails | Tagged , , | 2 Comments
  •  

    September 2010
    M T W T F S S
    « Jul    
     12345
    6789101112
    13141516171819
    20212223242526
    27282930