繁体   English   中英

如何在Ruby on Rails中显示ActiveRecord :: JDBCError的自定义错误消息?

[英]How to display custom error message for ActiveRecord::JDBCError in Ruby on Rails?

我的视图中有一个HTML表,用于create, update and delete名为Mast_Freq的表的记录。

该表的Primary key由表'AssFreq'和其他一些表中的外键'MastFreq'引用。 因此,当我尝试删除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

你可以试试这个

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

您可以通过将功能包含在begin / rescue / end块中来消除控制器或模型中的错误,如@ 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM