Friday, October 28, 2011

[Heroku] Access Rails's model in migration, heroku rake db:migrate, uninitialized constant

I wanted to use Rails's migration to add new column to a table and fill this column with default value.
add_column :students, :student_id, :integer 
Student.all.each { |s| s.update_attributes!(:student_id => s.id+10000) }
I run this locally.
rake db:migrate
It worked without any problem.

Then I deployed to Heroku and run;
heroku rake db:migrate
I found this error.
 uninitialized constant AddStudentIdToStudents::Student
After googling for a while, I found this blog post Heroku Migration Fails to Update Attributes: reset_column_information

The way to solve this issue(don't know why) is to open up the class inside migration file like this;
class AddStudentIdToStudents < ActiveRecord::Migration
  class Student < ActiveRecord::Base; end
  def change
    add_column :students, :student_id, :integer
    Student.all.each { |s| s.update_attributes!(:student_id => s.id+10000) }
  end
end
This works for me.

Note: Rails 3.1.0 

No comments: