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