Don’t try to be smarter than ActiveRecord

When you’re writing conditions for a finder in ActiveRecord, and you want to use an array of values for a sql in() statement, you might think to help ActiveRecord out and comma-separate the array values like this:

type_ids = [1, 2, 3]
Something.find(
  :all,
  :conditions => ['type_id in (?)', type_ids.join(',') ] )

Which will generate a sql fragment that looks like this:

[...] where events.status_id in (’1,2,3′) [...]

Well, this will work just fine if you’re using MySQL, but not so fine (read ‘at all’) if you’re using SQLite.  So, if you’re using MySQL for your development environment and SQLite for your test environment, like me, it will work fine in dev and fail in your tests.

So, instead, just let ActiveRecord’s sanitizers do their job and write:

Something.find(
  :all,
  :conditions => ['type_id in (?)', type_ids])

Your sanity will thank you.

Share
This entry was posted in Rails and tagged , , , , . Bookmark the permalink.

Comments are closed.