Active Record: library climate Shift (migration)

Source: Internet
Author: User
Tags table definition bit definition

Active Record:Climate migration of the information repository (migration)

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the U Niverse trying to produce bigger and better idiots. So far, the Universe is winning. -Rick Cook

Migrations (repository climate) allows you to modify the library structure using Ruby. Compared to the direct Access repository system using SQL to modify the structure (for example, using the PhpMyAdmin tool to modify), using migrations allows us to record the changes in the repository, each change is a migration record. Before migration, if you change the repository by hand, you have to notify other developers of the same change step as well. In addition, on the official server, you have to follow and perform the same changes. These steps, if not recorded, can be easily mistaken.

Migrations Will Self-track which changes have been done, and those that have not, you only need to add migration files, and then perform the Rake db:migrate is done. It'll figure out which migrations to run, so all the developers and the official servers will be able to easily sync with the latest repository structures. Another advantage is that migration is independent of the library system, so you don't need to be in trouble worries different kinds of language differences, like various types of the various information system. Of course, if you want to write an expert function on a particular repository, you can write SQL directly.

Add a migration file

Execute the following instructions, and you will be in the db/migrate/of the 20110203070100_migration_name.rb file.

rails g migration migration_name

Notice that in front of the migration_name.rb, there is an order of YYYYMMDDHHMMSS, which is used to indicate the order in which the line is executed. In earlier versions of Rails, the sequential order was named with the number of numbers in the version, but if there were many different branches that could have duplicate codes, the time stamp was used in the post-rails 2.1 version to allow rails to pay for the situation of many people.

Migration_name common naming methods have Add欄位名To表格名 or Remove欄位名From表格名 , but this does not have certain, can describe the purpose.

Let's open this file and see:

class MigrationName < ActiveRecord::Migration  def up  end  def down  endend

In this category, there are two kinds of methods that divide up and down. Where up will perform this migration, whereas the down will be executed when rolling back this migration. For example, when we add an Information Library table (table) on up, we can delete this table at down time.

Migration Available Methods

In the up or down method, we have the following methods to use:

Make changes to the information table:

    • Create_table (name, options) new information sheet
    • Drop_table (name) to remove the information sheet
    • Rename_table (Old_name, new_name) modify the information table name
    • Change_table Modifying the Information table linked fields bit

Change the information table linked fields bit:

    • Add_column (table, column, type, options) add a linked fields bit
    • Rename_column (table, Old_column_name, new_column_name) modify linked fields bit name
    • Change_column (table, column, type, options) modifies the form of the linked fields bit (type)
    • Remove_column (table, column) remove linked fields bit

Add and Remove indexes:

    • Add_index (table, columns, options) new index
    • Remove_index (table, index) remove index

Remember to index all external keys foreign key

Add and remove Table

When you execute the rails G model, rails will then add a new migration file. The above chapter produces categories migration as an example:

class CreateCategories < ActiveRecord::Migration    def change        create_table :categories do |t|          t.string :name          t.integer :position          t.timestamps        end                add_column :events, :category_id, :integer        add_index :events, :category_id    endend

The timestamps will create a time-linked fields bit called Created_at and Updated_at, which is a common use for rails. It will automatically create a new time for the information and update the time.

Suspect, how is this not used up and down method? Rails version 3.1 Adds a change way to intelligently handle most down of the situation, with the down exception of removing catrgories the information sheet and removing events the category_id linked fields bit, so there's no need to write up down it out. If Rails can't be judged, it will remind you not to use it when running rake db:migrate change and need to write up and down .

Modify Table

Let's try adding a linked fields bit:

rails g migration add_description_to_categories

Open DB/MIGRATE/20110411163049_ADD_DESCRIPTION_TO_CATEGORIES.RB

class AddDescriptionToCategories < ActiveRecord::Migration  def change    add_column :categories, :description, :text  endend

When done, the bundle exec rake db:migrate linked fields will actually be added to the repository.

Linked fields-bit definition of the information repository

To enable different repositories to be used, the following are the types of information in migration and the type of picture that the actual repository uses:

the form in Rails explain MySQL Postgres SQLite3
: string Finite length string varchar (255) Character varying (255) varchar (255)
: Text Unlimited length text Text Text Text
: integer Whole numbers Int (4) Integer Integer
: float Floating point numbers Float Float Float
:d Ecimal Ten-bit numbers Decimal Decimal Decimal
:d Atetime Date Time Datetime Timestamp Datetime
: Timestamp Time Stamp Chapter Datetime Timestamp Datetime
: Time Hours Time Time Datetime
:d ate Date Date Date Date
: Binary Two-bit Blob Bytea Blob
: Boolean Bollinger value tinyint Boolean Boolean
: References Take a look at the external keys of other table Int (4) Integer Integer

In addition, the linked fields bit also has some parameters that can be set:

    • :nullIf NULLis allowed, the preset is allowed
    • :defaultPreset value
    • :limitSpecifies the maximum value for string,text,integer,binary

For example:

create_table :events do |t|    t.string :name, :null => false, :limit => 60, :default => "N/A"    t.references :category # 等同於 t.integer :category_idend

Reference information: activerecord::connectionadapters::tabledefinition

Examples of linked fields-bit names

We've already introduced the Timestamps method will automatically add two time linked fields bits, Rails also retains a few of the names used as examples:

linked fields bit name Use
Id The primary key for the linked fields bit name
{tablename}_id The external key of the preset linked fields bit name
Created_at If you have this linked fields bit, rails will set the time for the new
Updated_at If you have this linked fields bit, rails will set the time to change
created_on If you have this linked fields bit, rails will set the time for the new
updated_on If you have this linked fields bit, rails will set the time to change
{Tablename}_count If you use the Counter Cache feature, this is the linked fields bit name
Type If you have this linked fields, rails will activate the STI feature (see Chapter ActiveRecord)
Lock_version If you have this linked fields, rails will activate the optimistic locking function (see ActiveRecord chapter)
Migration Paired Rake Task
    • Rake Db:create in accordance with the current RAILS_ENV environment to establish a repository
    • Rake Db:create:all builds all the environment's repositories
    • Rake Db:drop Delete the information in accordance with the current RAILS_ENV environment
    • Rake Db:drop:all Delete all environment's repositories
    • Rake Db:migrate Perform migration motion
    • Rake Db:rollback step=n back on n Migration motion
    • Rake Db:migrate:up version=20080906120000 perform a specific version of migration
    • Rake Db:migrate:down version=20080906120000 back to a specific version of migration
    • Rake db:version The migration version of the current repository
    • Rake db:seed db/seeds.rb Loading seed material

If you need to specify a RAILS environment, such as production, you can enter Rails_env=production rake db:migrate

Seed material Seeds

seed Material The meaning of this is that some of the information is necessary for the application to run the basic information, and these information we will put in db/seeds.rb this file. For example, let's start by adding some basic Category information:

# This file should contain all the record creation needed to seed the database with its default values.# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).## Examples:##   cities = City.create([{ name: ‘Chicago‘ }, { name: ‘Copenhagen‘ }])#   Mayor.create(name: ‘Emanuel‘, city: cities.first)Category.create!( :name => "Science" )Category.create!( :name => "Art" )Category.create!( :name => "Education" )

Input rake db:seed will execute this file. The usual time to do this is to build the repository and run out of migration .

Information migration

Migrations can not only be used to change the definition of the table, it is also very commonly used to climate the material. When adding or modifying a linked fields bit, somewhat often also needs to set the value of the new linked fields bit according to the existing information. At this time we will be using ActiveRecord to manipulate the information in migration.

But if you change the linked fields bit in migration and use this model to update the material, then the rails will be quick to get the linked fields bits of the information table, so you won't be reading the information table that you just modified. There are several methods to handle this:

The first is to call Reset_column_information to re-read the information table definition.

The second is to use Activereocrd::base to define a new blank Model in migration.

The third is to execute the arbitrary SQL by the function.

ProductionRun up MigrationAttention to things

When there is a lot of information, if there is a change to the library table ALTER TABLE , he will Lock table can not be written into, it may be difficult to run a few hours of pre-estimate. It is suggested to use staging server to test how long it will run with close to production information.

    • http://www.engineyard.com/blog/2011/making-migrations-faster-and-safer/
    • http://backstage.soundcloud.com/2011/05/introducing-the-large-hadron-migrator-3/
BulkParameters

:bulk => trueCan make it more efficient to migration the linked fields bit of the repository, and if you don't add this, or use it directly, and add_column rename_column remove_column so on, then Rails will break the SQL to perform, for example:

change_table(:users) do |t|  t.string :company_name  t.change :birthdate, :datetimeend

Will produce:

ALTER TABLE `users` ADD `im_handle` varchar(255)ALTER TABLE `users` ADD `company_id` int(11)ALTER TABLE `users` CHANGE `updated_at` `updated_at` datetime DEFAULT NULL

Plus :bulk => true :

change_table(:users, :bulk => true) do |t|  t.string :company_name  t.change :birthdate, :datetimeend

Will merge to produce a row of SQL:

ALTER TABLE `users` ADD COLUMN `im_handle` varchar(255), ADD COLUMN `company_id` int(11), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL

There is a lot of information about the amount of money in the library, there will be many of the difference in speed, you can reduce the library because the change was locked lock time.

Active Record: library climate Shift (migration) (RPM)

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.