Rails 迁移指南建议您在迁移中创建一个人造模型,如果您需要对数据库中的数据进行操作,例如:
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
问题是,在AddFuzzToProduct
类中,产品模型的名称将是AddFuzzToProduct::Product
. 我有以下情况:
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
问题是,在each
学生资料的块内,用户是零。激活记录器后,我可以看到 Rails 正在尝试执行以下查询:
RemoveFirstNameFromStudentProfile::User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."profile_id" = 30 AND "users"."profile_type" = 'RemoveFirstNameFromStudentProfile::StudentProfile' LIMIT 1
当然,这可以通过将User
andStudentProfile
向上移动一级来解决,例如:
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
我的问题是:将人造模型的定义移到迁移声明之外会对我造成任何问题吗?我在这里缺少什么吗?为什么 Rails 团队的人在迁移类中声明它们?