Re: multiple models from one controller.

s.ross
Sun, 22 Apr 2007 23:41:51 -0000

Read up on validates_associated[1]. Also consider:

begin
   order = order.new(params[:order])
   line_item = table2.new(params[:line_item])
   order.line_items << line_item
   order.save!
rescue
   # something went wrong
end

This is ''air code'' and clearly a simplistic example, but what
should
happen here is that you create a new order. orders has an associated
table, line_items (probably a has_many relationship). When you use
save!, an exception is created if there is a problem such as model
validation failure. Because you used validates_associated, this
bubbles failures in the associated item up. When the exception
happens, the transaction block causes a rollback, leaving the
database in its original state. The Rails dox [2] say that "save and
destroy are automatically wrapped in a transaction."

Best to test this in script/console and observe its actual behavior.

Hope this helps.

[1] http://railsmanual.org/module/
ActiveRecord::Validations::ClassMethods/validates_associated
[2] http://railsmanual.org/module/ActiveRecord%3A%3ATransactions%3A%
3AClassMethods

On Apr 22, 2007, at 4:24 PM, ikiini wrote:

>
> Hey all,
>
> I am new to Ruby on Rails and need some beyond basics help. I have a
> the agile web dev with rails 2nd ed. And i have looked at a few
> tutorials online. However none has covered real life webapps with
> multiple tables in a DB where some depend on others. let me cut to the
> chase. I have a app with 3 tables. 2 of the tables are directly
> related meaning that i can''t insert into one with out inserting
the
> corresponding values into the other. now i have figure out with some
> help from IRC how to do this. but now i have a problem. I need to have
> validattion on both models before the inserts are made. what is
> happening is that if validation passes on the 1st, that inserts then
> the 2nd fails and that doesn''t insert. so right there i have a
> problem. My question is how do i handle such a situation. Thanks for
> the help
>
> -B
>
>
> >