# Polymorphic associations and Validation

**URL:** <https://www.ruby-forum.com/t/polymorphic-associations-and-validation/130407>\
**Category:** Rails\
**Created:** [February 28, 2008, 12:10am UTC](https://www.ruby-forum.com/t/polymorphic-associations-and-validation/130407 "2008-02-28T00:10:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ivan\_Ukhov](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/977dab/32.png) [@Ivan\_Ukhov](https://www.ruby-forum.com/u/Ivan_Ukhov)\
**Post date:** [February 28, 2008, 12:10am UTC](https://www.ruby-forum.com/t/polymorphic-associations-and-validation/130407/1 "2008-02-28T00:10:08Z")

</div>

Hello there!

I have a question about polymorphic associations. Suppose we have a  
parent class Parent and a child class Child, to create a new object I  
do something like:

class Child …  
:has\_one :parent, :as =\> :resource  
:validates\_presence\_of :name  
…  
end

class Parent …  
:belongs\_to :resource, :polymorphic =\> true  
…  
end

child = Child.new  
parent = ParentClass.new  
parent.resource = child  
parent.save!

but when validation of Child fails, rails still try to execute “insert  
into parents (…, resourse\_id) … (…, NULL)”, and because my db  
does not allow resource\_id to be NULL, it raises a StatementInvalid  
exception instead of raising RecordInvalid (as it should be if the  
validation fails).

Am I doing something wrong or it’s just a bug of rails?

Thanks.
