1.Migration
Migrations是一種便利的方法,能以重現的方式隨時間推移改變數據庫schema. 使用Ruby Domain Specific Language (DSL),因此你不用手寫SQL,進而使你的schema和changes與數據庫獨立。
可以把每次migration看作是數據庫的一個新“版本”。A schema開始時什么都沒有,每次migration都會對其進行修改,以添加或刪除表、列或索引。Active Record知道如何沿著這條時間線更新schema,把它從歷史中任何時間點帶到最新版本
Active Record更新 db/schema.rb 文件,使其與數據庫的最新結構相匹配。例如:
# db/migrate/20240502100843_create_products.rb
class CreateProducts < ActiveRecord::Migration[7.2]def changecreate_table :products do |t|t.string :namet.text :descriptiont.timestampsendend
end
這個migration添加一個名為products的表,該表有一個名為name的string型列和一個名為description的text型列。還將默認添加名為id的主鍵列,因為它是所有Active Record models的默認主鍵。timestamps會添加created_at 和 updated_at列。
Migrations以文件形式存儲在 db/migrate 目錄中,每個migration class都有一個文件。
文件名的格式為YYYYMMDDHHMMSS_create_products.rb,包含標識migration的 U