Migration檔案不需要和Model一一對應,像我們來新增一個Migration檔案來新增一個資料庫欄位,請執行:
$ rails g migration add_status_to_events
如此就會產生一個空的 migration 檔案在 db/migrate 目錄下。Migration 有提供 API 讓我們可以變更資料庫結構。例如,我們可以新增一個欄位。輸入
rails g migration add_status_to_events
然後編輯這個Migration檔案:# db/migrate/20110519123819_add_status_to_events.rb class AddStatusToEvents < ActiveRecord::Migration def change add_column :events, :status, :string end end
接著執行
bundle exec rake db:migrate
就會在events表格中新增一個status的欄位,欄位型別是string。Rails會記錄你已經對資料庫操作過哪些Migrations,像此例中就只會跑這個Migration而已,就算你多執行幾次bundle exec rake db:migrate
也只會對資料庫操作一次。
数据扩展 添加字段
最新推荐文章于 2022-09-12 17:36:36 发布