2012-10-17 41 views
2

我正在使用chargify_api_ares gem來搜索Chargify訂閱。重定向如果沒有找到對象

@current_subscription = Chargify::Subscription.find_by_customer_reference(@dealer.id) 
redirect_to(dealers_path) unless @current_subscription 

然而,如果沒有訂閱發現它永遠不會使它對地方重定向因爲find_by_customer_reference吐出404,如果未發現任何下一行,但我想一些方法它返回nil取而代之的是,我可以將它轉到下一行,我將用戶從那裏重定向。

有誰知道我可以如何輕鬆地失敗或更好的方式我可以重定向用戶,如果沒有對象被發現?謝謝。

回答

5

大概的方法是提高一個ActiveRecord::RecordNotFound例外,它可以捕獲並變成一個重定向:

begin 
    @current_subscription = Chargify::Subscription.find_by_customer_reference(@dealer.id) 
rescue ActiveRecord::RecordNotFound 
    redirect_to dealers_path 
end 
+0

謝謝!這個伎倆。實際上我不得不「拯救ActiveResource :: ResourceNotFound」,但是。謝謝。 –

相關問題