数据扩展 添加字段

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的欄位,欄位型別是stringRails會記錄你已經對資料庫操作過哪些Migrations,像此例中就只會跑這個Migration而已,就算你多執行幾次bundle exec rake db:migrate也只會對資料庫操作一次。

Rails透過資料庫中的schema_migrations這張table來記錄已經跑過哪些Migrations


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值