每當我為用戶創建一個表時,它總是有一個 ID 列。我希望每當我創建一個新表時,總是將 costum_column(在我的情況下為 uuid)添加為列,就像 ID 一樣。
uj5u.com熱心網友回復:
(假設您在談論 ruby?? on rails)
如果您希望 id 成為 uuid,最簡單的方法是擁有以下內容
class MyMigration < ActiveRecord::Migration
create_table "my_table", id: :uuid do |t|
# ...
end
end
如果您希望所有 create_table 始終添加另一個自定義列,例如 public_id,那么您可以將猴子補丁添加到您的 create_table 方法
# initializers/custom_table_column.rb
module ActiveRecord
class Migration
class Current
module CustomColumnOnCreateTable
def create_table(*args)
add_custom_column = ->(t) { t.uuid("public_id", null: false) } # for example
if block_given?
super do |t|
add_custom_column.call(t)
yield compatible_table_definition(t)
end
else
super { |t| add_custom_column.call(t) }
end
end
end
prepend CustomColumnOnCreateTable
end
end
end
這個解決方案 IMO 的問題是你在隱藏東西。使用該方法的人(合作者或同事,尤其是資歷較淺的人)沒有預料到會出現這種情況,他們會在幾個小時內搜索這種意外行為的來源
IMO 一個更好的選擇是創建一個助手,它允許仍然手動呼叫它,但是在一行中,或者通過一個簡單的方法呼叫。所以沒有什么是隱藏的,但這很容易。
module ActiveRecord
class Migration
class Current
module CustomColumnOnCreateTable
def add_public_id_column(t)
t.uuid("public_id", null: false) # for example
end
end
prepend CustomColumnOnCreateTable
end
end
end
那么你可以
# my migration
# ...
def up
create_table :test, id: :uuid do |t|
add_public_id_column(t)
t.string :something_else
# ...
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/498042.html
