5

I created a model with an attribute "name" but I want to change it to "username". Everything I've read about database migrations involves creating a class or some complicated stuff. All I want to do is the equivalent of "UPDATE TABLE" in SQL. How do you run a one-time database migration to change this? I'm guessing it'd involve rails console and then some command?

3 Answers 3

9

First:

rails g migration rename_name_column_to_username

Then in the generated rename_name_column_to_username.rb migration file:

class RenameNameColumnToUsername < ActiveRecord::Migration
  def self.up
    rename_column :users, :name, :username
  end

  def self.down
    rename_column :users, :username, :name
  end
end

And then rake db:migrate

Sign up to request clarification or add additional context in comments.

Comments

3

If you haven't committed the code that originally created the "name" column, you can just go in to the old migration file that created that column and change name to username and then regenerate the schema.

But if you have committed the code, you should create a separate migration file that renames name to username.

This is important to keep track of the versioning of your database. So you should never really use manual SQL (ALTER TABLE ...) to change the schema.

Comments

0

Run rails g migration RenameNameToUsername, which will create a new file in db/migrate.

Open that file, and add this into the self.up section:

rename_column :tablename, :name, :username

Then run rake db:migrate

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.