# Polymorphic association question

**URL:** <https://www.ruby-forum.com/t/polymorphic-association-question/191512>\
**Category:** Rails\
**Created:** [July 13, 2010, 6:59pm UTC](https://www.ruby-forum.com/t/polymorphic-association-question/191512 "2010-07-13T18:59:36Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![joep](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/87869e/32.png) [@joep](https://www.ruby-forum.com/u/joep)\
**Post date:** [July 13, 2010, 6:59pm UTC](https://www.ruby-forum.com/t/polymorphic-association-question/191512/1 "2010-07-13T18:59:36Z")

</div>

Question from a relative newbie. I have the following models (rails -v  
Rails 2.3.8)

class Node \< ActiveRecord::Base  
belongs\_to :containable, :polymorphic =\> true  
end

class Root \< ActiveRecord::Base  
has\_one :node, :as =\> :containable

validates\_presence\_of :owner  
validates\_numericality\_of :owner, :only\_integer =\> true, :message =\>  
“can only be whole number.”  
validates\_inclusion\_of :owner, :in =\> 21…30, :message =\> “can only  
be between 21 and 30.”  
end

Now, from the console:

> > n=Node.new(:containable=\>Root.new(:owner=\>22), :name=\>“aaabz”)  
> > =\> #\<Node id: nil, parent\_id: nil, lft: nil, rgt: nil, containable\_id:  
> > nil, containable\_type: “Root”, name: “aaa”, permissions: “none”,  
> > created\_at: nil, updated\_at: nil\>
> 
> > n.save  
> > =\> true  
> > =\> #\<Node id: 66, parent\_id: nil, lft: 7, rgt: 8, containable\_id: 10,  
> > containable\_type: “Root”, name: “aaabz”, permissions: “none”,  
> > created\_at: “2010-07-13 13:55:35”, updated\_at: “2010-07-13 13:55:35”\>
> 
> > Root.find(10)  
> > =\> #\<Root id: 10, owner: 22, created\_at: “2010-07-13 13:55:35”,  
> > updated\_at: “2010-07-13 13:55:35”\>

I did not realize that both records (Node and the containable) would  
automatically be saved to the db when the container (Node) was saved,  
but it was a nice bonus. So this was all ok with me.

HOWEVER, the following also occurred:

> > n=Node.new(:containable=\>Root.new(:owner=\>1), :name=\>“aaab”)  
> > =\> #\<Node id: nil, parent\_id: nil, lft: nil, rgt: nil, containable\_id:  
> > nil, containable\_type: “Root”, name: “aaab”, permissions: “none”,  
> > created\_at: nil, updated\_at: nil\>
> 
> > n.save  
> > =\> true
> 
> > n  
> > =\> #\<Node id: 65, parent\_id: nil, lft: 5, rgt: 6, containable\_id: nil,  
> > containable\_type: “Root”, name: “aaab”, permissions: “none”,  
> > created\_at: “2010-07-13 13:47:19”, updated\_at: “2010-07-13 13:47:19”\>

That is, the containable record failed to validate, so it was not  
saved, while the container was ok and it WAS saved, leaving things in  
quite an unexpected condition.

I know I can code around this, but it seems quite odd. Am I missing  
something simple?

Thanks.
