簡體   English   中英

Rails嵌套模型驗證問題

[英]Rails nested model validation issue

我有以下包含一些驗證的收件人模型(為簡單起見,僅顯示了前兩個):

 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驗證僅在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_id或offer_acceptance_id。

是否有一種方法可以讓收件人模型知道該記錄是由要出售的商品保存的,例如,currency_to設置為“ usd”? 也就是說,以嵌套形式創建時,父屬性可以傳遞給子模型嗎?

我發現唯一需要做的就是在offers#create操作上添加關聯

@recipient = Recipient.new(offer_params[:recipient_attributes])
@recipient.offer = @offer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM