Rails belongs_to class_name hijinks

Quick Hits   Rails  

This will be short and sweet. If you're using a 'class_name' attribute on your 'belongs_to' association to make an alias for that field, make sure you capitalize it properly. I was getting a number of errors while running my specs, things like this:

NameError: uninitialized constant News::user

The problem was I had my 'belongs_to' relationship declared like this:

belongs_to :author, class_name: :user

When it should have been like this:

belongs_to :author, class_name: :User

That capital letter is very important! Now, once you've fixed that, you may start seeing more errors, like this:

ActiveModel::MissingAttributeError: can't write unknown attribute `author_id'

Which just means you either need to rename the foreign key in your table, or use the 'foreign_key' attribute to specify the current column name, like so:

belongs_to :author, class_name: :User, foreign_key: 'user_id'

This annoyed me for a good hour or so, so hopefully this will save somebody that same hassle in the future.