Rails Development Details (v) Migrations Data Migration

Source: Internet
Author: User
Tags rollback

1. Introduction

Using migration in rails makes it easy to manage the structure of your database. You can create databases, create tables, delete tables, add fields, delete fields, and organize your data.

Migration is a series of classes, all of which inherit the Activerecord::migration class.

Class Createproducts < activerecord::migration 
  def up 
    create_table:p roducts do |t| 
      T.string:name 
      t.column:d escription,: Text 
      t.timestamps 
    end 
     
  def down 
    drop_table: Products 
  End  

Above is a migration example. The code in the UP method will

Rake Db:migrate

executed afterwards.

The code in the Down method will

Rake Db:rollback

executed afterwards.

T.timestamps will automatically generate Created_at and Updated_at columns.

You can also make table structure modifications.

Class Addreceivenewslettertousers < activerecord::migration 
  def up 
    change_table:users do |t| 
      T.boolean:receive_newsletter,:d efault => false
    end 
    User.update_all ["Receive_newsletter =?", True] 
  End 
      
  def down 
    remove_column:users,: receive_newsletter 
  End 

rails3.1 creates a new method change, which is used primarily to create tables and columns, without writing a pair of up and down, and the database does not have to be down by using the Rake db:rollback rollback method.

1.1.migration offers a lot of ways

Add_column

Add_index

Change_column

Change_table

Create_table

Drop_table

Remove_column

Remove_index

Rename_column

If you want to roll back the migration changes to the database, you can use the Rake db:rollback command.

1.2.ActiveRecord Supported column types

: Binary

: Boolean

:d ate

:d Atetime

:d Ecimal

: float

: integer

:p Rimary_key

: string

: Text

: Time

: Timestamp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.