I recently had some very interesting failed migration which I would like to share with you here.
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
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!