Migration erros when truning on config.threadsafe!

When turning on config.threadsafe! in production environment and trying to migrate production database I get odd errors like uninitialized constant AddAdminToUsers::User, here is the migration file data:

class AddAdminToUsers < ActiveRecord::Migration   def self.up     User.create!(:username=> 'admin',:first_name=>"admin",:last_name=>"admin", :password=> 'admin@exam$',:password_confirmation=> 'admin@exam$')   end

  def self.down   end end

This error never shows up when that setting is off...

Ok just for the record, i found a similar thread regarding that here https://rails.lighthouseapp.com/projects/8994/tickets/2506-models-are-not-loaded-in-migrations-when-configthreadsafe-is-set , and all I did to fix it is to require the user model at the top of this migration file:

require 'user'

I'll just throw out the notion that this may not be the right solution.

In general, if you actually *use* a model to do something in a migration, you should define a minimal version of the model *inside* the migration class. For example:

class AddAdminToUsers < ActiveRecord::Migration    class User < ActiveRecord::Base; end    def self.up      User.create!(:username=>'admin',           :first_name=>"admin", :last_name=>"admin",           :password=>'admin@exam$',           :password_confirmation=>'admin@exam$')    end

   def self.down    end end

That way changes to the model or the database don't lead to odd failures later on -- like when a production deployment is several migration versions behind and tries to do some now incompatible things with an earlier migration. Think what would happen if the 'username' column were to be renamed to 'login' in a later migration and both needed to be applied.


Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com