2012-09-23 52 views
0

我有一個像這樣has_many手機的客戶模型;如何防止我最後的嵌套屬性被銷燬?

class Customer < ActiveRecord::Base 
    has_many :phones, as: :phoneable, dependent: :destroy 
    accepts_nested_attributes_for :phones, allow_destroy: true 
end 

class Phone < ActiveRecord::Base 
    belongs_to :phoneable, polymorphic: true 
end 

我想確保客戶始終至少有一個嵌套的手機型號。目前,我在瀏覽器中管理這些內容,但我想在服務器上提供備份(我遇到了一些沒有電話的客戶記錄,不太清楚他們是如何得到的,所以我需要一個後援) 。

我認爲這一點在模型中必須是可以實現的,但我不太確定如何去做。到目前爲止,我所有的嘗試都失敗了。我認爲手機模型中的before_destroy回調是我想要的,但我不知道如何編寫這個模型以防止模型被破壞。如果父模型已被銷燬,我也需要它來允許銷燬模型。任何建議?

回答

0

你可以這樣說:

before_destory :check_phone_count 

def check_phone_count 
    errors.add :base, "At least one phone must be present" unless phonable.phones.count > 1 
end 
相關問題