Sit back, relax, and enjoy the code.

Don’t try to be smarter than ActiveRecord

Posted: November 17th, 2008 | Author: gabe | Filed under: Rails | Tags: , , , , | Comments Off

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/Bookmark

Comments are closed.