回上一頁

Rails migration實用筆記整理

Rails 中的 Migration 是 Active Record 提供的一個功能,讓您可以透過 Ruby 程式碼來管理資料庫結構的變更。它就像資料庫的版本控制系統,讓您能夠追蹤、修改和回滾資料庫的變更。

Migration 的優點:

  • 版本控制: 每次資料庫結構的變更都會被記錄在一個 migration 檔案中,您可以輕鬆查看變更歷史、回滾到之前的狀態,或將變更應用到其他環境。
  • 團隊協作: Migration 檔案可以被納入版本控制系統 (如 Git),方便團隊成員共享和協作。
  • 可重複性: Migration 檔案可以被重複執行,確保不同環境 (開發、測試、正式) 的資料庫結構一致。
  • 安全性: Migration 提供了 updown 方法,讓您可以在變更出錯時安全地回滾。
  • 可維護性: Migration 檔案比直接修改 SQL 指令更易於閱讀和維護。

Migration 的常見用法:

  • 建立資料表 (create_table)
  • 刪除資料表 (drop_table)
  • 新增欄位 (add_column)
  • 刪除欄位 (remove_column)
  • 修改欄位 (change_column)
  • 重新命名資料表 (rename_table)
  • 新增索引 (add_index)
  • 刪除索引 (remove_index)
  • 執行 SQL 指令 (execute)
  

#production rails / rake 
RAILS_ENV=production rails db:migrate:status
RAILS_ENV=production rails db:migrate
RAILS_ENV=production rails g model xxx yyy
RAILS_ENV=production rails g migration add_{欄位}_to_{表}s {欄位}:{型態}
bundle exec rake db:migrate RAILS_ENV=production
bundle exec rails db:migrate RAILS_ENV=production

# create table
rails g model {model_name} coloumn:boolean

# add_column
rails g migration add_{欄位}_to_{表}s {欄位}:{型態}
rails g migration add_menu_product_source_to_menus menu_product_source:integer
rails g migration add_response_codes_to_user_payments response_codes:jsonb

# change_column ex.
rails g migration change_{欄位}_to_{表}s {欄位}:{型態}
	
# migration寫法 ex.  
def change    
  add_column :menus, :menu_product_source, :integer
  add_column :menus, :menu_contact, :text
  remove_column :menus, :button_color, :string
  remove_column :menus, :button_two_name, :string
  remove_column :menus, :button_two_url, :string
  remove_column :menus, :button_two_color, :string
	 
	# 改 table_name, Ex. users 變 customers
	rename_table :users, :customers  
	
	# drop table_name
	drop_table :users
end

def up
	add_column :users, :email, :string, first: true
end
def down
	remove_column :my_blogs, :column
end

# rails Rollback與注意事項
#提醒:在使用rollback時要切記,必須要在還沒有資料的時候 才能使用, 該表的資料會清空!!
rails db:rollback STEP=1
#上述STEP會依照照migration資料夾從最後順序往上進行rollback

# 操作 migration rollback table 流程
# VERSION 用下面指令查
rails db:migrate:status
rails db:migrate:down VERSION=
rails db:migrate:up VERSION=
or
rails db:migrate