# Clean way of creating and validating 2 related models in controller (with STI)?

**URL:** <https://www.ruby-forum.com/t/clean-way-of-creating-and-validating-2-related-models-in-controller-with-sti/141783>\
**Category:** Rails\
**Created:** [June 30, 2008, 4:10pm UTC](https://www.ruby-forum.com/t/clean-way-of-creating-and-validating-2-related-models-in-controller-with-sti/141783 "2008-06-30T16:10:26Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [June 30, 2008, 4:10pm UTC](https://www.ruby-forum.com/t/clean-way-of-creating-and-validating-2-related-models-in-controller-with-sti/141783/1 "2008-06-30T16:10:26Z")

</div>

Hi,

I’ve got really typical problem, but with small twist - need to create  
a Foo and Bar objects in a single form with validation of both  
objects, where:  
Foo.belongs\_to :bar  
Bar.has\_one :foo.

I’ve found really clean way to do it in this tutorial:

> **[params\[:fu\] #2 ) Put attributes into a different params key using fields\_for...](http://www.stephenchu.com/2008/03/paramsfu-2-put-attributes-into.html)**
>
> fields\_for is very useful for separating out your params: \<% form\_for @reader do | f | %\> \<%= f.text\_field :name % \> \<% fields\_...

Code looks like this:  
def create  
@foo = Foo.new params[:foo]  
@bar = @foo.build\_bar params[:bar] if @foo.is\_a? FooBar  
if @foo.save  
…  
end

But the problem is that Foo model has “validates\_presence\_of :bar\_id”  
validation, so calling @foo.save causes error on @foo.bar\_id. Another  
problem is that I’m using STI and Foo is related with Bar only if it’s  
of specific type, which complicates things a bit.

Removing “validates\_presence\_of :bar\_id” solves the problem -  
@foo.bar\_id is properly assigned and everything works great - but I’d  
really like to have this validation there - otherwise I’d have to  
change some code in other places (instead of checking for  
“foo.bar\_id”, I’m doing “foo.is\_a? FooBar” assuming that all FooBar  
objects have proper foo\_id assigned).

Any ideas?

Regards
