Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating models in rails / migrations

Let's say I used the following command to create a "User" model:

script/generate model User username:string

This creates the user.rb file along with the migration rb file to create the Users table. Now, I want to add an email column to my User model. What's the best way to do that? Do I do it manually and write the migration file by hand or is there a shortcut for doing it? If I write the migration by hand, do I have to name it the same way as the previous migration script (with a timestamp in front) to guarantee that it runs after the previous migration?

like image 387
Kevin Pang Avatar asked Jun 26 '10 19:06

Kevin Pang


People also ask

How does migration work in rails?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

What does Add_index do in rails?

add_index(table_name, column_name, **options) LinkAdds a new index to the table. column_name can be a single Symbol , or an Array of Symbols. The index will be named after the table and the column name(s), unless you pass :name as an option.

How do I rollback 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.


2 Answers

Don't worry about the timestamp. It will be generated automatically. You can do a

rails generate migration add_email_to_user email:string

This would automatically create a migration file which would look like this:

class AddEmailToUser < ActiveRecord::Migration
  def self.up
    add_column :email, :string
  end

  def self.down
    remove_column :email
  end
end

the file would have the timestamp in the format YYYYMMDDHHMMSS (For Rails 2.1 and above) appended in front of the filename.

like image 194
Garfield Avatar answered Sep 20 '22 15:09

Garfield


The Guide has information about generating migrations. If you use the rails generator, it will create correctly named files:

ruby script/generate migration AddEmailToUser email:string
like image 36
Bryan Ash Avatar answered Sep 20 '22 15:09

Bryan Ash