Rails nested model validation issue -
i have following recipient model containing validations (just showing first 2 keep simple):
 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 invalid format" },  if: "to_usd?"    def belongs_to_offer?     #check if recipient 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 ... and here offer model
class offer < activerecord::base   has_one :recipient   accepts_nested_attributes_for :recipient   validates_associated :recipient   .... as can see, aba_transit_number validation takes place if recipient.offer.currency_to === "usd". validation works fine when create new recipient on console so:
o = offer.create!(currency_to: "usd") r = recipient.create!(offer: o, name:"john") activerecord::recordinvalid: validation failed: aba transit number can't blank, aba transit number has invalid format, ... but when try nested form, validation takes place on recipient name validation. figured reason to_usd? returns false because since offer has not been created yet, there no offer_id or offer_acceptance_id.
is there way let recipient model know record being saved offer currency_to set "usd" example? is, can parent attributes passed child model when created in nested form?
i figured out thing needed done add association on offers#create action
@recipient = recipient.new(offer_params[:recipient_attributes]) @recipient.offer = @offer 
Comments
Post a Comment