I had a quick question about setting the default value of a column in a Rails migration to a non-static value.
I have a "Users" table that already has the columns id, first_name, and last_name, and I want to add a new column called "username" that defaults to the user's last name. This is what I currently have:
class AddLoginToUsers < ActiveRecord::Migration
def change
add_column :users, :username, :string, :default => :last_name
end
end
Clearly, this does not produce the intended result (it defaults to the string "last_name"). How would I go about setting the default to the row's last_name value?
Thanks in advance.
Not sure you can do that, you could instead add a before_validation
or before_save
callback in your User
model:
class User < ActiveRecord::Base
before_validation :create_username_if_missing
private
def create_username_if_missing
self.username = last_name unless username
end
end
And update all exisiting users after adding that callback:
User.where("username is null").each do |user|
user.update_attributes(username: user.last_name)
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.