When saving parent fails, children will still be updated

Hi all,

When submitting a master/detail form I first want to handle the children
before saving the parent.
There are has_many and belongs_to relations between the parent and the
children, so I can edit the children using (psuedo-)code like:
child.destroy for deleting, child.update_attributes for updating and
@parent.children.push(child) for adding child-records.
I update the parent by using:
if @parent.update_attributes(params[:parent])
flash[:notice] = ‘Parent was successfully updated.’
redirect_to(:action => “list”)
else
render :action => ‘edit’
end # if

The problem I’m facing at the moment is that when updating the parent
fails, the chances made to the children are still saved. I tried to
include the code in a transaction:
Parent.transaction do

all code

end

but this makes no difference.

What am I doing wrong? Hope someone can help me out on this.

Thanks in advance,

Patrick

Patrick B. wrote:

else
but this makes no difference.
You have to raise an exception to rollback a transaction.
So you must code something like:

begin
Parent.transaction do
# update children
@parent.attributes = params[:parent]
@parent.save!
flash[:notice] = ‘Parent was successfully updated.’
redirect_to :action => “list”
end
rescue
render :action => ‘edit’
end

To avoid a transaction you’d have to check everything for
validity before you start any saving, and then hope there’s
no database errors.


We develop, watch us RoR, in numbers too big to ignore.

On 6/13/06, Patrick B. [email protected] wrote:

Hi all,

When submitting a master/detail form I first want to handle the children
before saving the parent.
snip
The problem I’m facing at the moment is that when updating the parent
fails, the chances made to the children are still saved. I tried to
include the code in a transaction:
Parent.transaction do

all code

end

but this makes no difference.

What am I doing wrong? Hope someone can help me out on this.

Which db are you using? A certain popular ‘database’ doesn’t enable
transactions by default.

Isak

Isak H. wrote:

Which db are you using?

I’m using mySQL 4.1 and created InnoDB tables. I still have to try Mark
Reginald J.’ suggestion, I think that’ll do it. Let you know later
today.

Mark Reginald J. wrote:

You have to raise an exception to rollback a transaction.

Thanks Mark, I replace my code and it works.

Great!