Rails 嵌套模型验证问题
Rails nested model validation issue
我有以下包含一些验证的收件人模型(为了简单起见,只显示前 2 个):
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?
returns false 因为报价尚未创建,所以没有 offer_id 或 offer_acceptance_id.
有没有办法让收件人模型知道记录正在由 currency_to 设置为 "usd" 的报价保存?即,在嵌套形式创建时,父属性是否可以传递给子模型?
我发现唯一需要做的就是在商品上添加关联#create 操作
@recipient = Recipient.new(offer_params[:recipient_attributes])
@recipient.offer = @offer
我有以下包含一些验证的收件人模型(为了简单起见,只显示前 2 个):
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?
returns false 因为报价尚未创建,所以没有 offer_id 或 offer_acceptance_id.
有没有办法让收件人模型知道记录正在由 currency_to 设置为 "usd" 的报价保存?即,在嵌套形式创建时,父属性是否可以传递给子模型?
我发现唯一需要做的就是在商品上添加关联#create 操作
@recipient = Recipient.new(offer_params[:recipient_attributes])
@recipient.offer = @offer