2015-09-30 33 views
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”的商品?这是,父类属性可以在嵌套形式创建时传递给子模型?

+0

为什么我检查'offer.currency_to'是因为有不同的原因取决于该字段的验证。如果该值为“美元”,则应用某些验证;如果该值为“人民币”,则为其他验证。 –

回答

0

我想通了,那需要做的唯一的事情是添加上#创建行动计划书的关联

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