Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One time change model attribute (column name) in Ruby on Rails

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?

like image 538
Geoff Avatar asked Jun 05 '11 18:06

Geoff


People also ask

How do I change the column name in Ruby on Rails?

You can use the change method with the rename_column definition in your migrations files to update a single column name in your database.

How do I rollback a migration in Rails?

To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.

What is a migration in Ruby?

Migrations are a convenient way to alter your database schema over time in a consistent way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent. You can think of each migration as being a new 'version' of the database.


2 Answers

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

like image 117
Zabba Avatar answered Oct 24 '22 04:10

Zabba


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.

like image 26
Fredrik Avatar answered Oct 24 '22 04:10

Fredrik