Created
April 28, 2011 09:34
-
-
Save webgago/946088 to your computer and use it in GitHub Desktop.
Миграции в RoR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # миграции генерятся при генерации модели | |
| # $ rails generate model Post title:string content:text author_id:integer | |
| # генерирует db/migrate/{TIME}_create_posts.rb | |
| class CreatePosts < ActiveRecord::Migration | |
| def self.up | |
| create_table :posts do |t| | |
| t.string :name | |
| t.text :content | |
| t.integer :author_id | |
| end | |
| add_index :posts, :author_id | |
| end | |
| def self.down | |
| drop_table :posts | |
| end | |
| end | |
| # или руками | |
| # $ rails generate migration AddColumnAndColumn2ToModel column:string column2:integer | |
| # генерирует db/migrate/{TIME}_add_column_and_column2_to_model.rb | |
| class AddColumnAndColumnAndColumn2ToModel < ActiveRecord::Migration | |
| def self.up | |
| add_column :models, :column, :string | |
| add_column :models, :column2, :integer | |
| end | |
| def self.down | |
| remove_column :models, :column2 | |
| remove_column :models, :column | |
| end | |
| end | |
| # соответственно есть класс ActiveRecord::Migration | |
| # у него есть методы | |
| ActiveRecord::Migration.up | |
| ActiveRecord::Migration.down | |
| # внутри этих методов доступны следующие манипуляции с БД | |
| # create_table | |
| # change_table | |
| # drop_table | |
| # add_column | |
| # change_column | |
| # rename_column | |
| # remove_column | |
| # add_index | |
| # remove_index | |
| # запуск миграций | |
| # $ rake db:migrate - выполняется migration.up | |
| # $ rake db:rollback - выполняется migration.down | |
| # перед первой миграцией в БД добавляется таблица | |
| # CREATE TABLE schema_migrations | |
| # ( | |
| # "version" character varying(255) NOT NULL | |
| # ) | |
| # в version хранится хронология миграций | |
| # 20100906143751 -> db/migrate/20100906143751_add_column_and_column2_to_model.rb | |
| # 20100906143752 -> db/migrate/20100906143752_add_column3_and_column4_to_another_model.rb | |
| # 20100906143759 -> db/migrate/20100906143759_add_column3_and_column4_to_model.rb | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment