简体   繁体   中英

Update database data inside a Rails migration

Is possible to update database data inside a migration?

I have this migration:

class FixTokenAuth < ActiveRecord::Migration
  def change
    unless column_exists? :users, :provider
      add_column :users, :provider, :null => false
    end
    unless column_exists? :users, :uid
      add_column :users, :uid, :null => false, :default => ""
    end
    unless column_exists? :users, :tokens
      add_column :users, :tokens, :text
    end
  end
end

And I have also to add indexes

add_index :users, [:uid, :provider],     :unique => true

Of course the migration fail: uid is "" per default and it can't be unique.

After the creation of the column I need to execute a block on my User model:

User.all.each{|u|
  u.provider = "email"
  u.save!
}

Doing this 'uid' field is filled by data.

Is possible to add something to a migration?

The migration is just plain ruby code, which gets executed, so the best thing you could do is change the change method into up and down . In these methods you can safely write your updating code after the add_column statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM