2011-05-30 63 views
1

我有一個教師模型accept_nested_attributes_for klasses。如果klass中有用戶並且我想打印驗證消息,我不希望能夠刪除該klass。rails 3 - 在銷燬驗證之前接受嵌套的屬性

這是我...

class Teacher < ActiveRecord::Base 
    accepts_nested_attributes_for :klasses, :reject_if => proc { |a| a['name'].blank? }, :allow_destroy => true 
end 

class Klass < ActiveRecord::Base 

    belongs_to :teacher 
    has_many :users 
    before_destroy :reject_if_has_users 

    private 

    def reject_if_has_users 
     if users.length > 0 
     errors.add_to_base "You cannot delete this class as it contains users." 
     false 
     else 
     true 
     end 
    end 

end 

我希望當我嘗試從包含當我使用accepts_nested_attributes_for並傳遞「klasses_attributes」用戶老師取出克拉斯驗證失敗= > {「0」=> {「name」=>「test」,「_destroy」=>「1」,「id」=>「17183」} hash。

如果我沒有error.add_to_base行,上述方法將阻止klass被刪除。它不會導致驗證消息顯示。當我有這條線時,它並不妨礙刪除。

感謝,

回答

1

確認刪除記錄時,保存記錄,只有當沒有發生。我在其中一個項目中處理這個問題的方式是在模型中引發異常,然後從控制器中的異常中解救出來並顯示閃光警報。就像這樣:

型號:

class Klass < ActiveRecord::Base 
    before_destroy :reject_if_has_users 

    private 

    def reject_if_has_users 
    raise "You cannot delete this class as it contains users." if users.length > 0 
    end 
end 

教師控制器:

def update 
    # Code for updating the teacher 
rescue RuntimeError => e 
    redirect_to teacher_url(@teacher, :alert => e.message) and return false 
end 
+0

我不是調用destroy方法,我節省了老師的記錄,可以包括刪除klasses的哈希值遭到移除神奇地通過accep_nested_attributes_for。例如。 「klasses_attributes」=> {「0」=> {「name」=>「test」,「_destroy」=>「1」,「id」=>「17183」} – Tim 2011-05-30 04:00:11

+0

恩,對不起,問題足夠小心。我會重寫我的答案... – Mischa 2011-05-30 04:08:47

+0

我更新了我的答案,但它不是很乾淨。您應該在代碼中添加一些註釋,明確發生了什麼。我很樂意看到更好的解決方案。祝你好運。 – Mischa 2011-05-30 04:19:58