為什麼呢?因為 migration 是永久留在那裡的,但是某些 class 是在未來可能被刪掉的,所以一個好的 migration file 要能夠讓 scope 維持在 migration file 裡
> While migrations contain the full history of the database schema for a project, they are always run in the context of the current codebase. Referencing a model constant, while tempting, can lead to issues down the road. - Upcase
Bad example
```rb
class AddAdminFlagToUsers < ActiveRecord::Migration
def up
add_column :users, :admin, :boolean, default: false
User.update_all(admin: false)
change_column_null :users, :admin, false
end
def down
remove_column :users, :admin
end
end
```
1. User 可能未來不存在,這樣 migration 會 failed
2. 一個好的 practice 在裡面,migration 要分兩階段,設完 boolean all false 才設 null: false
與其用 class, 直接使用 connection instance 執行 sql 在這裡會是比較好的做法:
```rb
class AddAdminFlagToUsers < ActiveRecord::Migration
def up
add_column :users, :admin, :boolean, default: false
connection.update(<<-SQL)
UPDATE users SET admin = 'f'
SQL
change_column_null :users, :admin, false
end
def down
remove_column :users, :admin
end
end
```
https://thoughtbot.com/upcase/decks/4/flashcards/23
沒有留言:
張貼留言