Validating a polymorphic association for a new record

Posted on September 30, 2011

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.


3 Replies to "Validating a polymorphic association for a new record"

  • kimerseen
    October 13, 2011 (3:52 am)

    it did work for me 🙁

  • Ray
    November 7, 2012 (9:23 am)

    Thanks for the pointer, I tried inverse_of first, and it did work for me. I have the problem that one association depends on the parent of the associated object.

  • Yuriy
    April 30, 2013 (5:49 am)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.