The Rails migration guide, suggests you create a faux model inside the migration, if you need to operate on the data from the database, like:
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 thing is, inside the AddFuzzToProduct
class, the name of the Product model 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 thing is, inside the each
block for the student profile, user is nil. After I activated the logger, I can see that Rails is trying to do the following query:
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 fixed by moving the User
and StudentProfile
up one level, like 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 the faux models outside of the declaration of the migration cause any problems for me? Is there something I'm missing here? Why did the guys from the Rails team declare them inside the migration class?