2011-01-20 72 views
1

我與後續的代碼一個Rails應用程序:刪除回形針附件,除非它是最後一個

class Rig < ActiveRecord::Base 
    has_many :rig_pictures, :dependent => :destroy 

    accepts_nested_attributes_for :rig_pictures, 
           :allow_destroy => true, 
           #we reject blank pictures unless they have to be deleted 
           :reject_if => lambda { |a| a['picture'].blank? && !a['_destroy'] } 

    validate :has_beween_1_and_x_pictures 
private 

    def has_beween_1_and_x_pictures 
    errors.add_to_base("must not have more than 8 pictures") if rig_pictures.size > 8 
    errors.add_to_base("must have at least 1 picture") if rig_pictures.size < 1 
    end 
end 

我的問題是「必須至少有1張」驗證。如果用戶處於編輯窗體並刪除了他的所有圖片,驗證將不會失敗,因爲此時它不知道要刪除它。

所以我的問題是:我如何確保驗證只考慮真實圖片而不是我想要刪除的圖片?

Thx。

回答

1

也許你可以嘗試RidPicture模型中的驗證。類似

def before_destroy 
    if (self.rid.rid_pictures.count <= 1) 
     errors.add_to_base "Almost one image" 
     false 
    end 
end 

東西沒有測試

+0

不得不因爲需要改用另一種策略。我將在下一次嘗試這一點......有一件事是肯定的:PaperClip真的需要更好的管理來刪除,我想我必須自己去處理它! – Alain 2011-01-22 04:33:08