Validate nested object only if the main object requires its presence

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))

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.

Answers


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.


Need Your Help

Query Entity Framework for list of dynamic type

c# entity-framework generics reflection

When querying entity framework for all objects of a given type, you'd do something like this:

mysql query results divide into group

php mysql

From mysql query, I want make 5 results as a group wrap into a li . how to? thanks

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.