0

ユーザーモデルとユーザーモデルhas_oneプロファイルモデルがあります。また、user.phoneとuser.profile.phoneがありますが、user.phoneを削除したいので、user.profile.phoneのみを使用します。

user.phoneを削除する前に、user.phoneが空白でない場合は、user.phoneをuser.profile.phoneにコピーします。次にuser.phoneを削除します。

例えば:

user.phone = 123
user.profile.phone = 234

移行後:

user.phone will be removed
user.profile.phone = 123 - 234

この目的のための適切な移行は何ですか?

4

4 に答える 4

1

これを試して

class YourMigration < ActiveRecord::Migration
 def self.up
   User.find_each do |user|
 user.profile.update_attributes(:phone => user.phone) unless user.phone.blank?
   end
   remove_column :users, :phone
 end

 def self.down
  add_column :users, :phone, :string
 end
end
于 2013-01-10T14:05:22.187 に答える
0

データベースがそれほど大きくない場合は、次のように簡単に実行できます。

User.includes(:profile).all.each{ |u| u.profile.phone = u.phone unless u.phone.nil? }

コンソールで。または、移行で次のようにsmthを記述できます。

def change
  User.includes(:profile).all.each{ |u| u.profile.phone = u.phone unless u.phone.nil? }
  remove_column :users, :phone
end
于 2013-01-10T13:56:13.493 に答える
0
class YourMigration < ActiveRecord::Migration
  def self.up
     User.where("phone IS NOT NULL").includes(:profiles).each{ |u| u.profile.phone = u.phone}
     remove_column :users, :phone
  end
  def self.down
    add_column :users, :phone, :string
  end
end
于 2013-01-10T15:05:56.687 に答える
0

不必要な苦痛を生み出すため、移行でモデルを使用しないことを好みます。

同じプロジェクトで作業している多くの人が、移行でモデルを使用してコミットするとします。他の人がユーザーモデルを削除するか、モデルに検証を適用してコミットを実行します。彼または他の人が移行を実行しようとすると、使用したモデルが存在しないか、何らかの検証が行われているために失敗する可能性があります。

したがって、移行ではSQLステートメントを使用することをお勧めします。

class SomeMigartion < ActiveRecord::Migration
  def self.up
    execute('update profiles p inner join users u on p.user_id = u.id set p.phone = u.phone where u.phone is not null')
    remove_column :users, :phone
  end

  def self.down
     add_coulmn :users, :phone
  end
end
于 2013-01-11T03:07:06.510 に答える