ActiveRecord Migrations – Editing a column that was just added

I recently had some very interesting failed migration which I would like to share with you here.

The Problem

Assume you want to create an ActiveRecord migration which adds a flag column to table some_models and changes the values of some rows to that column in the table:

running rake db:migrate generates an error:

undefined method `relation' for nil:NilClass

On the line SomeModel.first.update_attribute(:flag,  false)

So what really happened here?

At the start of the migration, Rails loads the SomeModel class into memory and maps methods to columns in the DB. Since at that time SomeModel does not have an active column, no method is generated to access/change it. After we add the active column we try to update it which generates the above error. I wish they’d make it more descriptive though.

How To Bypass The Error

The solution lies within
method which refreshes the class-db method mapping.

after the add_column statement solves the problem!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s