Here’s my model hierarchy:
Page- has_many :media (media can be
TextMedium,ImageMedium,VideoMedium… (STI))- each media has_one :attachment (
ImageAttachment,VideoAttachment… (different tables))
- each media has_one :attachment (
- has_many :media (media can be
I want to have a form to create a page with:
- an
ImageMedium(not required) - a
VideoMedium(not required) - other attributes…
An ImageMedium validates the presence of its attachment.
Same for a VideoMedium.
But the page don’t validates the presence of an ImageMedium or VideoMedium media.
My form looks something like this (“pseudo code”):
form_for page
fields_for :image_media
fields_for :attachement
image_field
fields_for :video_media
fields_for :attachement
video_field
PROBLEM:
-
if I fill in the form completely, it works great, and I can create the page with its media and attachments.
-
but if I don’t fill in the video field for instance, I would still like my page to be created (because the video media is not required by the page). BUT it won’t be, because the video media requires the presence of its attachment, so it’s invalid, so the page is invalid…
QUESTION:
How can I ignore the fact that the video media validation fails and still create the page?
EDIT:
i found an answer:
class Page < ActiveRecord::Base
accepts_nested_attributes_for :video_media, reject_if: ->(attributes) { attributes["attachment_attributes"]["video"].blank? }
end
If you have a better one, please share.
I found an answer:
If you have a better one, please share.