AR - custom error handling

I have this code in a controller:

respond_to do |format|
  if @currency.save
    flash[:notice] = 'Currency was successfully created.'
    format.html { redirect_to(@currency) }
    format.xml  { render :xml => @currency,
      :status => :created, :location => @currency }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @currency.errors,
      :status => :unprocessable_entity }
  end

I have this code in the associated AR model:

save

Override AR save method to catch DBMS specific errors

such as uniqueness constraint violations

def save
super
rescue ActiveRecord::StatementInvalid => this_exception
errors.add_to_base(hll_ar_exception(this_exception))
end

When I attempt to add a record in violation of a uniqueness constraint
then hll_ar_exception catches the dbms error and returns. If the error
is something else then it raises the original error again.

I expect that if the custom error handler returns a value to the
instance save method then a Rails error is raised with the provided text
and displayed in the view. However, this does not happen. Instead I
receive a record added successfully notice, even though the new row is
not actually inserted.

Further, if I make this one change to the model code:

save

Override AR save method to catch DBMS specific errors

such as uniqueness constraint violations

def save
super
rescue ActiveRecord::StatementInvalid => this_exception
errors.add_to_base(hll_ar_exception(this_exception))
puts hll_ar_exception(this_exception) ##### <=== add this line
end

Then I do get the error message returned from hll_ar_exception displayed
in the view as an error with the appropriate field highlighted.

Can somebody explain to me what is going on?

On Jun 18, 5:22 pm, James B. [email protected]
wrote:

When I attempt to add a record in violation of a uniqueness constraint
then hll_ar_exception catches the dbms error and returns. If the error
is something else then it raises the original error again.

You are using the return value of save. in the case when your rescue
block is invoked, the return value of save is what your rescue clause
evaluates to and it would seem that errors.add_to_base always
evaluates to something true. You need to return false from that block
(which your puts statement does since puts always evaluates to nil)

Fred

Frederick C. wrote:

You are using the return value of save. in the case when your rescue
block is invoked, the return value of save is what your rescue clause
evaluates to and it would seem that errors.add_to_base always
evaluates to something true. You need to return false from that block
(which your puts statement does since puts always evaluates to nil)

Fred

Thanks.

Regards,