Transaction Failures

Hey,

I’ve got a multiple model (4) form on my site.

I have the controller handling the creation with a transaction. I do
this because if one object can’t save I don’t want any of them saved
and need to be able to quit the entire transaction without making any
permanent db calls.

The problem I find is. If a validation fails on an object without the
transaction present. The page refreshes with rails generated
validation errors. With the transaction present I don’t know how to
send it back to the page with errors present. But again without the
transaction if there is a problem all good objects get saved to the db
and the bad one does not.

So the problem is: If the transaction fails. I need the form page to
load with validation errors.

I use the code below:

def create
begin
ActiveRecord::Base.transaction do
@dealer = Dealer.new(params[:dealer])
@dealer.save!
@user = @dealer.users.build(params[:user])
@user.role_id = 3
@dealer.addresses.build(params[:mailing_address])
#@dealer.addresses.create(params[:billing_address])
end
rescue ActiveRecord::RecordInvalid => invalid
flash[:notice] = “Vehicle was not created”
@dealer = Dealer.new
@user = User.new
render :action => “new”
end

if ! @dealer.new_record?
  flash[:notice] = "Dealer, User and addresses saved!"
  redirect_back_or_default login_path
end

end

cheers.

Found my problem immediately after posting.

In:

rescue ActiveRecord::RecordInvalid => invalid
flash[:notice] = “Vehicle was not created”
@dealer = Dealer.new
@user = User.new
render :action => “new”
end

Should be:

rescue ActiveRecord::RecordInvalid => invalid
flash[:notice] = “Vehicle was not created”
render :action => “new”
end

Creating new objects seems to get blank all the fields. As well I was
missing separate <%= f.error_messages %> for each model type.