szimek
2008-Jun-30 14:09 UTC
Clean way of creating and validating 2 related models in controller (with STI)?
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: http://www.stephenchu.com/2008/03/paramsfu-2-put-attributes-into.html 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 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---