Ron M
Ron M

Reputation: 803

Use model field for default value in Rails migration

In my Rails 4 application, I would like to add a 'username' field to my User model. Since I already have users in the database, I'd like to use their email (which is currently a part of the model) as the default username in my migration. Here's what I have so far:

class AddUsernameColumnToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string, null: false
    add_index :users, :username, unique: true
  end
end

So, I'd like do something akin to:

add_column :users, :username, :string, null: false, default: this.email

But that code is not valid. Any thoughts? Thanks in advance.

Upvotes: 1

Views: 73

Answers (1)

user3409950
user3409950

Reputation: 373

You can solve it like this

class AddUsernameColumnToUsers < ActiveRecord::Migration
  def up
    add_column :users, :username, :string, null: false
    add_index :users, :username, unique: true
    query = 'UPDATE users SET username = email'
    ActiveRecord::Base.connection.execute(query)
  end
  def down
    remove_column :users, :username
  end
end

Upvotes: 2

Related Questions