So I have a typical Rails model with accepts_nested_attributes_for with presence validation
(snippets)
class Book < ActiveRecord::Base
  ...
  has_one :cover
  accepts_nested_attributes_for :cover, allow_destroy: true
  validate :require_cover
  def require_cover
    errors.add('', 'You must have a cover for the book.') if self.cover.blank?
  end
  ...
end
This works and validates okay on the first step when I'm creating. But when I try to edit it and click delete on the cover (clicking delete adds _destroy true) and save it, it deleted the cover but the validation regarding presence has passed already.
I think what happened was:
No validation again regarding the no cover
Have I done this incorrectly? Is there another way to implement this? Or how do I revalidate this scenario (like, after the save and destroy that has happened, there would be another validation to say that the resulting object is now invalid)?
I found the fix to my question, I was right that the save doesn't take into account those that are tagged as _destroy.
This link describes the problem better and has the answer to it too. http://homeonrails.com/2012/10/validating-nested-associations-in-rails/
Basically he rejected those that are marked for destruction and counted the remaining ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With