Respect my table name prefix

What’s wrong with this line of Ruby on Rails code?

Car.find(:all, :conditions => ['cars.year = ?', @year])

If you’re doing your own, internal application, nothing major is wrong. However if your application is meant for distribution and end-user-deployment, you’re making dangerous assumptions about the database by hardcoding the table name.

Rails provides an easy way to add table name pre- and suffixes for people who need to run multiple applications from the same database. This happens shared hosting environments where the amount of allowed databases is often limited. If someone were to set a custom table name prefix (or suffix) the above code would break.

Luckily, Rails also provides you with the tools to not hardcode SQL. Please, start using them. Occasionally raw SQL can be necessary, but for the love of the benevolent god of DRY, don’t hardcode table names.

The above line of code isn’t agile, it’s fragile. You cannot make this assumption about the database. You need to do something like

Car.find(:all, :conditions => ["#{Car.table_name}.year = ?", @year])

and rejoice from having made your application more portable and customizable.

Sidenote: This also applies to the actual Rails codebase. As far as I know fixtures, eager loading, and migrations all fail when you have set a table_name_prefix and/or table_name_suffix.

This message was brought to you by Jacks unbridled frustration with having to fix up numerous files to get Typo running with a table_name_prefix. Again.

Update: And just like that, I became a Typo contributor :)