Миграции базы данных в Rails

Frederick Cheung, “Rails Database Migrations”, public translation into Russian from English More about this translation.

See also 112 similar translations

Translate into another language.

Participants

and_rew3069 points
alexbaumgertner188 points
GremL1N60 points
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next
1 2 3 4 5 6 7 8 9 10 11 12

Rails Database Migrations

Миграции базы данных в Rails

History of edits (Latest: alexbaumgertner 1 year, 9 months ago) §

Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You’d also have to keep track of which changes need to be run against the production machines next time you deploy.

Миграции -- это удобный способ поддерживать базу данных структурированной и организованной. Вы можете редактировать SQL-код вручную, но тогда вы должны будете четко объяснить другим разработчикам, что нужно пойти и выполнить ваш SQL-код. Вам также придется отслеживать все изменения внесенные другими разработчиками.

History of edits (Latest: GremL1N 1 year, 9 months ago) §

Active Record tracks which migrations have already been run so all you have to do is update your source and run rake db:migrate. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database.

Active Record отслеживает какие миграции были уже применены, вам всего лишь надо обновить исходные тексты и запустить rake db:migrate, а Active Record сам выполнит миграции, которые должны быть применены. В процессе выполнения будет также обновлен файл db/schema.rb, чтобы соответствовать структуре базы данных.

History of edits (Latest: and_rew 1 year, 9 months ago) §

— update your source видимо имеется ввиду обновление кода всего проекта и вместе со всем кодом придет код новых миграций, а потом уже rake db:migrate GremL1N

Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record’s functionality) it is database independent: you don’t need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.

Миграции позволяют описать преобразования на языке Ruby. Важным является (как и для большинства функционала Active Record) независимость от базы данных: нет нужды помнить специфический синтаксис CREATE TABLE или SELECT * (хотя можно опуститься до уровня "сырого" SQL для конкретной базы данных). Например, можно использовать SQLite3 в процессе разработки, а MySQL в промышленной среде.

History of edits (Latest: GremL1N 1 year, 9 months ago) §

You’ll learn all about migrations including:

Мы изучим всё о миграциях, в том числе:

History of edits (Latest: and_rew 1 year, 9 months ago) §

— может "узнаем"? GremL1N

* The generators you can use to create them

Генераторы для их создания.

History of edits (Latest: and_rew 1 year, 9 months ago) §

* The methods Active Record provides to manipulate your database

Методы Active Record для изменения базы данных.

History of edits (Latest: and_rew 1 year, 9 months ago) §

* The Rake tasks that manipulate them

Rake-задачи для управления ими.

History of edits (Latest: and_rew 1 year, 9 months ago) §

— Rake-задачи GremL1N

* How they relate to schema.rb

Как они влияют на schema.rb

History of edits (Latest: and_rew 1 year, 9 months ago) §

1 Anatomy of a Migration

Анатомия миграций

History of edits (Latest: and_rew 1 year, 9 months ago) §

— "Миграции: что внутри?" and_rew

Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:

Прежде, чем погрузиться в детали миграций, приведем несколько примеров их использования:

History of edits (Latest: and_rew 1 year, 9 months ago) §

class CreateProducts < ActiveRecord::Migration def self.up create_table :products do |t| t.string :name t.text :description t.timestamps end end def self.down drop_table :products end end

class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.string :name
t.text :description
t.timestamps
end
end
def self.down
drop_table :products
end
end

History of edits (Latest: GremL1N 1 year, 9 months ago) §

This migration adds a table called products with a string column called name and a text column called description. A primary key column called id will also be added, however since this is the default we do not need to ask for this. The timestamp columns created_at and updated_at which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table.

Эта миграция создает таблицу Products со строковым столбцом name и текстовым столбцом description. По-умолчанию, также добавляется первичный ключ с именем id (это можно явно не указывать). Автоматически будут созданы столбцы отметок времени created_at и updated_at. Откат этой миграции состоит в простом удалении таблицы.

History of edits (Latest: and_rew 1 year, 9 months ago) §
Pages: ← previous Ctrl next
1 2 3 4 5 6 7 8 9 10 11 12

© Frederick Cheung. License: Creative Commons Attribution-Share Alike 3.0