TOP

Validating a polymorphic association for a new record

Currently, in Rails, if you have a validates_associated on a model with accepts_nested_attributes_for, it will fail when creating a new record. (It fails because the foreign key is nil … because the object doesn’t exist yet.) Normally, using inverse_of solves this problem. However, with polymorphic associations, this doesn’t work. What would the point of defining the inverse_of a polymorphic object when polymorphism allows the associated object to be anything?

There are a couple bugs for Rails about this, but there isn’t a clear solution and the issues have been closed. Fortunately, you can use ObjectSpace to find the parent object and only validate the polymorphic id if the parent isn’t a new record.

References:

1 comment. Leave a Reply

  1. kimerseen

    it did work for me :(

Leave a Reply

Your email is never published nor shared.

You may use these HTML tags and attributes:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">