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


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:

Code looks like this: def create   @foo = params[:foo]   @bar = @foo.build_bar params[:bar] if @foo.is_a? FooBar   if   ... end

But the problem is that Foo model has "validates_presence_of :bar_id" validation, so calling 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?