transactions with two models

Hi,

In Agile Web Development with Rails section on Transactions (p 381) there are two main examples.

1) making changes in two records in the same database table 2) making changes in two records each in a different *database*

I want to do what is in between: changes in two records each in a different table of the same database. Suppose they are apples and oranges tables.

How do I write this?

Do I need to be as elaborate as this and will it work?

apple = Apple.find(:first) orange = Orange.find(:first)

Apple.transaction(apple) do   Orange.transaction(orange) do     apple.update_attributes(params[:apple])     orange.update_attributes(params[:orange])   end end

Or can I just write something much simpler like this?

Apple.transaction(apple, orange) do   apple.update_attributes(params[:apple])   orange.update_attributes(params[:orange]) end

Will the above be a problem since orange is not an Apple?

In the rails docs there is something even simpler

transaction do   apple.update_attributes(params[:apple])   orange.update_attributes(params[:orange]) end

but I think this version won't restore the apple and orange instances back to their previous state if the transaction fails.

What I don't understand is the class name that preceeds ".transaction". Does that class name make a transaction for just that table or with the entire *database* associated with that table?

Any help greatly appreciated.

Thanks, Peter

Peter Michaux wrote:

I want to do what is in between: changes in two records each in a different table of the same database. Suppose they are apples and oranges tables.

[...]

Or can I just write something much simpler like this?

Apple.transaction(apple, orange) do   apple.update_attributes(params[:apple])   orange.update_attributes(params[:orange]) end

This should work. Though the usage of instances as parameters to the transaction method is deprecated - check the docs.

Will the above be a problem since orange is not an Apple?

Yes, the transaction affects the database connection not the individual tables.

In the rails docs there is something even simpler

transaction do   apple.update_attributes(params[:apple])   orange.update_attributes(params[:orange]) end

but I think this version won't restore the apple and orange instances back to their previous state if the transaction fails.

Because this behaviour is deprecated.

You can check your development log to see exactly what queries are executed, that should show you the transactions also.