0

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.

1
  • Remember that the migration is just sending SQL commands to your database platform, so first you'll need an idea of what you even want those commands to be. You can accomplish what you're trying to do with triggers or SQL Server's computed columns, but I strongly recommend you forgo database trickery altogether and handle this in the application layer, like in @mind.blank's answer. Commented May 9, 2013 at 6:32

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.