Tuesday, June 12, 2007

Multiple Tables

Recently I had a problem with real life webapps withmultiple tables in a DB where some depend on others. I had a app with 3 tables. 2 of the tables are directlyrelated meaning that i can't insert into one with out inserting thecorresponding values into the other. I figured out with somehelp from IRC how to do this. but needed to have validattion on both models before the inserts are made. what was happening is that if validation passes on the 1st, that inserts then the 2nd fails and that doesn't insert. So question is how do i handle such a situation.

Answer , I found after some research and discussing in Forums

I Read up on validates_associated[1]. and 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 associatedtable, 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 anddestroy are automatically wrapped in a transaction."Best to test this in script/console and observe its actual behavior.

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

Thanks Guys

No comments: