簡化的例子是我有幾個類繼承自一個Asset類,這是一個ActiveRecord模型。當我在其中一個子類上使用create或create!時,一個欄位的 db 層和 ActiveRecord 層驗證都將被忽略。
資產表有一個type欄位null: false,資產模型有validates_presence_of :type,也有attribute :type, default: self.name。
如果我new在子類(例如 Item)上使用它,它的行為符合預期,我會得到一個Item欄位type設定為"Item". 如果我使用create或create!具有有效屬性,則不應用默認值,忽略驗證,并且我得到一個type欄位為nil.
奇怪的是,其他驗證得到尊重。如果我嘗試創建沒有name屬性的新專案,validates_presence_of :name則會正確引發驗證錯誤。
以下是一些精簡的代碼片段以供參考:
class CreateAssets < ActiveRecord::Migration[6.0]
def change
create_table :assets do |t|
t.string :type, null: false
t.string :name
# ...
end
end
end
class Asset < ApplicationRecord
enum type: {
Item: :Item,
Accessory: :Accessory,
Component: :Component,
Consumable: :Consumable,
}
attribute :type, default: self.name
validates_presence_of :name
validates_presence_of :type
end
class Item < Asset
# ...
end
i = Item.create({ ... })
i.type
#nil
i.persisted?
#true
i.valid?
#false
i = Item.new({ ... })
i.type
#"Item"
i.valid?
#true
uj5u.com熱心網友回復:
'type' 是 ActiveRecord 中的保留列名,因為它用于指示單表繼承(STI)。如果您不打算使用 STI,您應該選擇不同的列名,否則 STI 行為會干擾您在此處嘗試執行的操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/529724.html
標籤:轨道上的红宝石红宝石
