The Rails migration guide offers you to create an artificial model within the migration if you need to work with data from a database, for example:
class AddFuzzToProduct < ActiveRecord::Migration class Product < ActiveRecord::Base end def change add_column :products, :fuzz, :string Product.reset_column_information Product.all.each do |product| product.update_attributes!(:fuzz => 'fuzzy') end end end
The fact is that inside the AddFuzzToProduct class, the product model name will be AddFuzzToProduct::Product . I have the following situation:
class RemoveFirstNameFromStudentProfile < ActiveRecord::Migration class StudentProfile < ActiveRecord::Base has_one :user,:as => :profile end class User < ActiveRecord::Base belongs_to :profile,:polymorphic => true,:dependent => :destroy end def up StudentProfile.all.each do |student| # I need to do some work on the user object as well as on the student object user = student.user ... # do some stuff on the user object end end end
The fact is that inside the each block for the student profile, the user is zero. After I activated the registrar, I see that Rails is trying to execute the following request:
RemoveFirstNameFromStudentProfile::User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."profile_id" = 30 AND "users"."profile_type" = 'RemoveFirstNameFromStudentProfile::StudentProfile' LIMIT 1
Of course, this can be eliminated by moving User and StudentProfile to the same level, for example, in:
class StudentProfile < ActiveRecord::Base has_one :user,:as => :profile end class User < ActiveRecord::Base belongs_to :profile,:polymorphic => true,:dependent => :destroy end class RemoveFirstNameFromStudentProfile < ActiveRecord::Migration def up StudentProfile.all.each do |student| ... end end end
My question is: can moving the definitions of fake models beyond the migration declaration cause any problems for me? Is something missing here? Why did the guys from the Rails team declare them in the migration class?