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