Roberto Pezzali
Roberto Pezzali

Reputation: 2504

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?

Upvotes: 0

Views: 89

Answers (1)

Daniel Schmidt
Daniel Schmidt

Reputation: 11921

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_columnstatements.

Upvotes: 1

Related Questions