2014-05-03 68 views
0

讓我們的代碼幾行從控制器:現在Ruby on Rails:檢查互聯網連接是打開還是關閉?

class VendorsController < ApplicationController 
    def new 
    @vendor = Vendor.new 
    end 

    def create 
    @vendor = Vendor.new(params[:vendor]) 
    if @vendor.save 
     VendorMailer.registration_confirmation(@vendor).deliver 
     flash[:success] = "Vendor Added Successfully" 
     redirect_to amain_path 
    else 
     render 'new' 
    end 
    end 
end 

,在localhost當我在off方面,它告訴我的socket error(如預期)錯誤,但如果我做一個條件:

def create 
    @vendor = Vendor.new(params[:vendor]) 
    if @vendor.save 
    if (internet is connected) 
     flash[:success] = "Vendor Added Successfully mail have been send" 
     VendorMailer.registration_confirmation(@vendor).deliver 
     redirect_to amain_path 
    else 
     flash[:success] = "Vendor Added Successfully mail is not send" 
     redirect_to amain_path 
    end 
    else 
    render 'new' 
    end 
end 

如果你幫我,我會友好的。

回答

2

我不喜歡你檢查連接。正如你所說的,當沒有連接到rails時,遠程郵件服務器(或dns)的rails會拋出一個異常。所以你應該捕獲這個異常並相應地處理它。

def create 
    @vendor = Vendor.new(params[:vendor]) 
    if @vendor.save 
    begin 
     VendorMailer.registration_confirmation(@vendor).deliver 
     flash[:success] = "Vendor Added Successfully" 
     redirect_to amain_path 
    rescue SocketError => e 
     flash[:success] = "Vendor Added Successfully mail is not send" 
     redirect_to amain_path 
    end 
    else 
    render 'new' 
    end 
end 
+0

你能告訴我我們可以拯救哪種類型的錯誤嗎? –

+0

@SNEHPANDYA您提到過'SocketError',所以就是其中之一。在那段代碼中,並不是很多事情都會出錯,所以捕捉所有東西都是一個很好的主意。你可以做的是拯救所有的錯誤,並記錄他們得到你的案件。 – xlembouras