ruby-on-railsvalidationnested-formsnested-attributesfields-for

Rails - How to prevent deleting all children records of a parent


Listing < AR
  has_many :images
  accepts_nested_attributes_for :images, :allow_destroy => true
  validate :validate_image_count

  def validate_image_count
    errors.add_to_base("too few") if images.length < 1
  end
end

Image < AR
  belongs_to :listing
end

In my Listing#edit form I use fields_for to provide fields for all the images along with checkboxes to delete images. This is working fine. I want to enforce a check such that a listing is valid only if it had at least one image and at most 6.

In my current setup I can go to edit and delete all the images, and then update the listing.

I have tried using a validation as shown above but thats not being called. Could be just the way nested_attributes work in rails. Whats the best way to enforce this check?


Solution

  • as the images won't be deleted when you call the validation method it would return true on the image length. You can use marked_for_destruction?

    def validate_image_count
        errors.add_to_base("too few") self.images.any? { |i| i.marked_for_destruction? }
    end