Forum: Ruby on Rails multiple models from one controller.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
87edf9f01d07327e9ce8f6d0fba3dda4?d=identicon&s=25 ikiini (Guest)
on 2007-04-23 01:26
(Received via mailing list)
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

Ef0db53920b243d6758c2f6b1306df0d?d=identicon&s=25 Steve Ross (cwd)
on 2007-04-23 01:42
(Received via mailing list)
Read up on validates_associated[1]. Also consider:

   order =[:order])
   line_item =[:line_item])
   order.line_items << line_item!
   # something went wrong

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.

87edf9f01d07327e9ce8f6d0fba3dda4?d=identicon&s=25 ikiini (Guest)
on 2007-04-23 02:28
(Received via mailing list)
i just found exactly what i need on the rails forum and it works
great. Check out this link.
thanks however for your very quick response.

This topic is locked and can not be replied to.