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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.