Миграции базы данных в Rails | Participants
|
- Statistics
- Participants
- Translate into Russian
- Translation result
- Translated in draft, editing and proof-reading required.
If you do not want to register an account, you can sign in with OpenID.
Rails Database Migrations | ||
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-код. Вам также придется отслеживать все изменения внесенные другими разработчиками. | |
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, чтобы соответствовать структуре базы данных. | |
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 в промышленной среде. | |
You’ll learn all about migrations including: | — может "узнаем"? — GremL1N | |
* The generators you can use to create them | ||
* The methods Active Record provides to manipulate your database | ||
* The Rake tasks that manipulate them | — Rake-задачи — GremL1N | |
* How they relate to schema.rb | ||
1 Anatomy of a Migration | — "Миграции: что внутри?" — and_rew | |
Before I dive into the details of a migration, here are a few examples of the sorts of things you can do: | Прежде, чем погрузиться в детали миграций, приведем несколько примеров их использования: | |
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 | |
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. Откат этой миграции состоит в простом удалении таблицы. |
© Frederick Cheung. License: Creative Commons Attribution-Share Alike 3.0

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