简体   繁体   English

具有多态关联的accepts_nested_attributes_for

[英]accepts_nested_attributes_for with polymorphic association

Is there any way to halt saving of child before parent. 有什么办法可以阻止孩子在父母面前得救。

I am using accepts_nested_attributes_for with polymorphic association. 我使用带有多态关联的accepts_nested_attributes_for

I used multiple options validates_presence_of :parent_id , validates_assoicated :parent but none are working. 我使用了多个选项validates_presence_of :parent_idvalidates_assoicated :parent但是没有一个起作用。

For example, I do have a class 例如,我有一堂课

Class Person
  include HasPhoneNumbers
  ..
end


module HasPhoneNumbers
 def self.included(kclass)
   kclass.has_many :phone_numbers, :as => :callable, :dependent => kclass == Person ? :destroy : :nullify
 end
 klass.accepts_nested_attributes_for :phone_numbers, :reject_if => lambda {|pn| pn.keys.any?{|k| k.to_sym != :id && pn[k].blank?} }
end


class PhoneNumber
  belongs_to :callable, :polymorphic => true
end

So while saving person due to validation in person object, it was not saving. 因此,虽然由于对个人对象的验证而保存了个人,但并没有保存。 However, child(phone_number) was saving. 但是,child(phone_number)正在保存。 So I need to restrict it to not save child(phone_number) before parent(person) saves. 因此,我需要限制它在保存父(人)之前不保存子(电话号码)。

I did try multiple options using validates_presence_of and validates_associated , but none are working for me. 我确实使用validates_presence_ofvalidates_associated尝试了多个选项,但是没有一个对我有用。

@person = Person.new(params[:person])
ActiveRecord::Base.transaction do
  person.save!
end

Wrapping your saves within a transaction should roll back the phone number save if the person fails validation. 如果该人未通过验证,则将您的保存保存在交易中应回退电话号码保存。

Reference: ActiveRecord Transactions 参考: ActiveRecord事务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM