sharma_a sharma_a - 29 days ago 11
Ruby Question

Set nickname to name in downcase in RAILS migration

I'm using a User Model in which name column is there, but now I want to add a nickname column with default of nickname being the name of the user in downcase. How this can be achieved?

Answer

Since migration files are ruby files, you can use the rails models inside the migration files also,

class AddNicknameToUser < ActiveRecord::Migration
  def up
    add_column :users, :nickname, :string
    User.find_each do |user|
      user.nickname = user.try(:name).downcase
      user.save!
    end
  end

  def down
    remove_column :users, :nickname
  end
end

You can also use,

User.find_each do |user|
      user.update_attributes(:nickname => user.try(:name).downcase)
end
Comments