我有以下收件人模型包含一些验证(只显示前两个以保持简单):
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_id或offer_acceptance_id。
有没有办法让收件人模型知道记录是通过货币设置为“usd”的商品保存的?也就是说,当以嵌套形式创建时,父属性是否可以传递给子模型?
答案 0 :(得分:0)
我发现需要做的唯一事情就是在商品上添加关联#create action
@recipient = Recipient.new(offer_params[:recipient_attributes])
@recipient.offer = @offer