2014-09-05 150 views
0

我有兩個相關的類是這樣的:保存子對象時,要保存防止父對象失敗

class Purchase < ActiveRecord::Base 
    has_many :actions 

    before_create do |p| 
    self.actions.build 
    end 
end 

class Action < ActiveRecord::Base 
    belongs_to :purchase 

    before_save do |a| 
    false 
    end 
end 

Action類塊防止其儲蓄。我在考慮做Purchase.create會失敗,因爲它不能保存子對象。但它不保存Action,它提交Purchase。如何防止在子對象中出現錯誤時保存父對象?

+0

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_associated – 2014-09-05 20:18:43

+0

謝謝,但這並沒有改變任何東西。 – lunr 2014-09-05 21:51:18

回答

0

事實證明,你必須顯式地回滾事務,來自子對象的錯誤不會傳播。所以,我結束了:

class Purchase < ActiveRecord::Base 
    has_many :actions 

    after_create do |p| 
    a = Action.new(purchase: p) 
    if !a.save 
     raise ActiveRecord::Rollback 
    end 
    end 
end 

class Action < ActiveRecord::Base 
    belongs_to :purchase 

    before_save do |a| 
    false 
    end 
end 

注意到,我也改變了before_create回調after_create。否則,因爲belongs_to同時,將節省的父母,你會得到一個SystemStackError: stack level too deep.

0

嘗試使用此代碼Purchase類:

validate :all_children_are_valid 
def all_children_are_valid 
    self.actions.each do |action| 
    unless action.valid? 
     self.errors.add(:actions, "aren't valid") 
     break 
    end 
    end 
end 

還是在Purchase類使用validates_associated

validates_associated :actions 
0

如果你的業務邏輯,你不能沒有任何動作保存進貨,然後在購買行爲中添加出席驗證器

validates :actions, length: {minimum: 1}, presence: true