delete Paperclip attachment unless it is the last one
I have a rails app with the follow code:
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_t开发者_StackOverflow中文版o_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
My problem is the "must have at least 1 picture" validation. If the user is in the Edit form and delete all his picture, the validation will not fail because at that point, it does not know what I want to delete it.
So my question is: how can I make sure the validation only considers the real pictures and not those I want to delete?
Thx.
Maybe You could try a validation in the RidPicture Model .
Something similar to
def before_destroy
if ( self.rid.rid_pictures.count <= 1)
errors.add_to_base "Almost one image"
false
end
end
not tested
精彩评论