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.