0
我有一個包含一些驗證(只顯示第2保持簡單)以下收件人型號:Rails的嵌套模型驗證問題
class Recipient < ActiveRecord::Base
belongs_to :offer
belongs_to :offer_acceptance
validates :name, presence: true
validates :aba_transit_number, presence: true, aba_checksum: true, format: { with: /\A((0[0-9])|(1[0-2])|(2[1-9])|(3[0-2])|(6[1-9])|(7[0-2])|80)([0-9]{7})\Z/, message: "has an invalid format" }, if: "to_usd?"
def belongs_to_offer?
#Check if recipient is from offer
offer_id != nil && offer_acceptance_id == nil
end
def to_usd?
(belongs_to_offer? && offer && offer.currency_to === "usd") || (!belongs_to_offer? && offer_acceptance && offer_acceptance.offer.currency_from === "usd")
end
...
這裏是發售模型
class Offer < ActiveRecord::Base
has_one :recipient
accepts_nested_attributes_for :recipient
validates_associated :recipient
....
由於你可以看到,aba_transit_number
驗證只發生在recipient.offer.currency_to === "usd"
。
o = Offer.create!(currency_to: "usd")
r = Recipient.create!(offer: o, name:"John")
ActiveRecord::RecordInvalid: Validation failed: Aba transit number can't be blank, Aba transit number has an invalid format, ...
但是當我嘗試這從一個嵌套形式,即發生在接收者的唯一驗證名稱的驗證:當我創建像這樣的控制檯上的一個新的收件人 驗證工作正常。我認爲原因是to_usd?
返回false,因爲由於offer還沒有被創建,所以沒有offer_id或offer_acceptance_id。
有沒有辦法讓收件人模型知道記錄被貨幣保存爲「usd」的商品?這是,父類屬性可以在嵌套形式創建時傳遞給子模型?
爲什麼我檢查'offer.currency_to'是因爲有不同的原因取決於該字段的驗證。如果該值爲「美元」,則應用某些驗證;如果該值爲「人民幣」,則爲其他驗證。 –