更改对不同模型的引用 rails 迁移
Change reference to different model rails migration
如何迁移 Referral
table 以指向现有数据库的 PatientProfile
id 而不是 User
id(即想迁移所有现有行)?
class User
belongs_to :profile, polymorphic: true
has_many :referrals
class PatientProfile
has_one :user, as: :profile
class Referral
belongs_to :user
我可以通过简单地进行迁移并将 user_id
列重命名为 patient_profile_id
并更改模型中的引用来完成此操作,但这不会迁移现有记录。
我不会简单地更改列名。我会做这样的事情
class AddPatientProfileToReferrals < ActiveRecord::Migration
def up
add_column :referrals, :patient_profile_id
add_index :referrals, :patient_profile_id
Referral.reset_column_information
Referral.includes(:user).find_each do |referral|
referral.update_attribute(:patient_profile_id, referral.user.profile_id)
end
remove_column :referrals, :user_id
end
end
您可能想确保推荐人有一个用户,您可以简单地逆向编写 down 方法。
如何迁移 Referral
table 以指向现有数据库的 PatientProfile
id 而不是 User
id(即想迁移所有现有行)?
class User
belongs_to :profile, polymorphic: true
has_many :referrals
class PatientProfile
has_one :user, as: :profile
class Referral
belongs_to :user
我可以通过简单地进行迁移并将 user_id
列重命名为 patient_profile_id
并更改模型中的引用来完成此操作,但这不会迁移现有记录。
我不会简单地更改列名。我会做这样的事情
class AddPatientProfileToReferrals < ActiveRecord::Migration
def up
add_column :referrals, :patient_profile_id
add_index :referrals, :patient_profile_id
Referral.reset_column_information
Referral.includes(:user).find_each do |referral|
referral.update_attribute(:patient_profile_id, referral.user.profile_id)
end
remove_column :referrals, :user_id
end
end
您可能想确保推荐人有一个用户,您可以简单地逆向编写 down 方法。