Avoiding Confusing Naming Issues in Rails

One of the most confusing causes of bugs in Rails apps is when names collide with Rails conventions.

Here’s a few places that I can think of:

###Model

  1. Don’t name any columns ending with _id unless these are foreign keys and integer values. If you use the nilify_blanks gem, which is super useful when you have tables with unique indexes that allow nulls, then columns ending with _id and _count are ignored by default.
  2. Don’t name any column type, as that’s reserved.

###Controller

  1. Don’t accidentally create any controller methods that end in _url or _path as those will conflict with route helpers.

What other names are reserved in Rails? What sort of subtle bugs have you seen related to this?

In the case of Models, point 2 (Don’t name any column type, as that’s reserved.), if you do want a type column that’s not used to compute a class name, you place change the inheritance column name with:

class Model < AR::Base
  self.inheritance_column = :anything_else
end

Then you’re type column will behave as a attribute with no special issues

Just ran into this one. I created a partial named _flash.haml. Inside that partial, flash was always nil. I renamed the partial _flash_messages.haml. That fixed this.

Moral of the story: Don’t name a partial (or probably any view) the same name as any helper method available in the view.

Here’s a summary of suggestions that I got on related forums:

Other possibly reserved ones are:

  • record
  • attribute or attributes
  • transaction