## 遷移
* <a name="schema-version"></a>
應使用版本控制工具記錄 `schema.rb` (或 `structure.sql` )的變化。
<sup>[[link](#schema-version)]</sup>
* <a name="db-schema-load"></a>
應使用 `rake db:scheme:load` 而不是 `rake db:migrate` 來初始化空數據庫。
<sup>[[link](#db-schema-load)]</sup>
* <a name="default-migration-values"></a>
應在遷移文件中設置默認值,而不是在應用層面設置。
<sup>[[link](#default-migration-values)]</sup>
```Ruby
# 差——在應用中設置默認值
def amount
self[:amount] or 0
end
```
雖然許多 Rails 開發者建議在 Rails 中強制使用表的默認值,但這會使數據受到許多應用 bug 的影響,因而導致應用極其難以維護。考慮到大多數有一定規模的 Rails 應用都與其它應用共享數據庫,保持應用的數據完整性幾乎是不可能的。
* <a name="foreign-key-constraints"></a>
務必使用外鍵約束。在 Rails 4.2 中,ActiveRecord 本身已經支持外鍵約束。
<sup>[[link](#foreign-key-constraints)]</sup>
* <a name="change-vs-up-down"></a>
書寫建設性的遷移(添加表或列)時,應使用 `change` 方法而不是 `up` 或 `down` 方法。
<sup>[[link](#change-vs-up-down)]</sup>
```Ruby
# 老式寫法
class AddNameToPeople < ActiveRecord::Migration
def up
add_column :people, :name, :string
end
def down
remove_column :people, :name
end
end
# 新式寫法(更好)
class AddNameToPeople < ActiveRecord::Migration
def change
add_column :people, :name, :string
end
end
```
* <a name="no-model-class-migrations"></a>
不要在遷移中使用模型類。由于模型的變化,模型類也一直處在變化當中,過去運行正常的遷移可能不知什么時候就不能正常進行了。
<sup>[[link](#no-model-class-migrations)]</sup>