2013-06-12 43 views
1

我在我的查看中有一個HTML表,以create, update and delete表的記錄爲Mast_Freq如何在Ruby on Rails中顯示ActiveRecord :: JDBCError的自定義錯誤消息?

該表的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 
+1

一種方法是在呼叫周圍放置一個救援塊來刪除,並從中提出所需的自定義消息。 – mcfinnigan

+0

是的,但請舉個例子。我是ROR的新手。仍在學習。謝謝。 – Vinay

回答

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 
+0

嗨,謝謝。但仍然令人困惑。我更新了問題並提供了我的控制器的示例。請看看並糾正我。 – Vinay

+1

刪除開始/救援/結束塊,只需要有rescue_from行和jdbc_error方法,如果不需要,可以從jdbc_error消息中刪除異常對象,它是一個可選變量,可讓您訪問錯誤。 – Matt

+0

我仍然收到了相同的錯誤頁面。 :-( – Vinay

1

你可以試試這個

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

+0

我是否需要在模型或視圖中執行此條件? – Vinay

+0

在開始的控制器中,你必須編寫所有代碼,就像在java中嘗試捕獲謝謝 –

+0

嗨,謝謝,我添加了我的控制器。請看一看。 – Vinay

相關問題