1

我的视图中有一个 HTML 表,create, update and delete用于显示名为Mast_Freq.

该表的 被表和其他一些表Primary key中的外键引用。所以,当我尝试删除一些记录时,我收到如下错误消息。'MastFreq''AssFreq'MastFreq

ActiveRecord::JDBCError: [Sybase][JDBC Driver][SQL Anywhere]Primary key for row in table 'MastFreq' is referenced by foreign key 'MastFreq' in table 'AssFreq': DELETE FROM "MastFreq" WHERE "MastFreq"."Frequency_Code" = 'A'

如何向用户显示自定义错误消息而不是此错误消息。不应删除此记录。

Frequency_Code是表的主键MastFreq

Controller:
----------
class Asset::MastFreqsController < AssetController

  rescue_from ActiveRecord::JDBCError, :with => :jdbc_error

  def destroy
    begin
      @asset_master_frequency = Asset::MastFreq.find(params[:id])
      result = @asset_master_frequency.destroy

      respond_to do |format|
    format.html{ redirect_to :action => :index}
    format.json{ render :json => result}
      end
    rescue ActiveRecord::JDBCError
    end
  end

  protected
  def jdbc_error(exception)
    flash[:error] = "You Cannot delete this Frequency Code" + exception.inspect
    redirect_to asset_master_frequencies_path
  end
end
4

2 回答 2

1

如@user2463570 所述,您可以通过在开始/救援/结束块中包含功能来挽救控制器或模型中的错误。

但是由于您想向用户显示消息,您可以通过添加以下行来捕获控制器中特定类型的所有错误:

rescue_from ActiveRecord::JDBCError, :with => :jdbc_error

def jdbc_error(exception)
  flash[:error] = 'There was an error.......' + exception.inspect
  redirect_to root_url 
end

并在页面上显示错误闪烁

<%= flash[:error] %>

这里有更多信息:ActiveSupport/Rescuable/ClassMethods.html

包括您的代码:

Controller:
----------
class Asset::MastFreqsController < AssetController

  rescue_from ActiveRecord::JDBCError, :with => :jdbc_error

  def destroy
    @asset_master_frequency = Asset::MastFreq.find(params[:id])
    result = @asset_master_frequency.destroy

    respond_to do |format|
      format.html{ redirect_to :action => :index}
      format.json{ render :json => result}
    end        
  end

protected
  def jdbc_error
    flash[:error] = 'You Cannot delete this Frequency Code'
    redirect_to asset_master_frequencies_path
  end
end
于 2013-06-12T09:36:36.000 回答
1

你可以试试这个

begin
===
your code
==
rescue ActiveRecord::JDBCError
puts "your custom error messages"
end

于 2013-06-12T09:31:41.740 回答