Sunday, September 11, 2011

"find_by_sql" can be devil

Rails’ find_by_sql is the devil. Ninety nine percent of the time find_by_sql is unnecessary and problematic, but it’s sooo seductive. I can’t even begin to count the ways that find_by_sql can cause trouble, but here’s a few:

Plugins like acts_as_paranoid rely on developers *not* using the back door to get around the dynamic conditions to exclude deleted rows.
There quite a few gotchas, ie: “SELECT * FROM users JOIN another_table …” won’t work because ActiveRecord will use the last ID field, not the first.
Logic “hidden” in find_by_sql is not reusable (as compared to a fancy association, etc)
It offends my aesthetic sense. We all like to pretend our ORM layer isn’t leaky.. don’t we?

Think you need find_by_sql? Ask yourself the following questions:

Can I just use :include, :select, :join, :conditions or some combination of the above?
Should this be an association? (perhaps with :conditions and :select on it? Maybe :readonly?)

No comments:

Post a Comment