0

I'm looking for the preferred way, and unique column to an existing table. I also want to add a unique index to the table. Before adding the index though, I obviously need to add data to the column to prevent the index creation from failing.

Here is the situation:

class AddUsernameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string, null: false

    # Need Data here! And don't want to do something like this:
    # User.each { |u| u.update_attribute(:username, u.email }

    add_index  :users, :username, unique: true
  end
end

I know using ruby code to populate the data is possible, there are lots of examples of that, but I keep reading that it isn't such a good idea. Are there any options other than something similar to the above?

4

1 回答 1

0

would the following work for your situation?

class AddUsernameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string, null: true

    execute("UPDATE users SET username = email")
    change_column :users, :username, :string, null: false

    add_index  :users, :username, unique: true
  end
end
于 2013-03-30T18:29:05.717 回答