2010-09-03 48 views
4

解決這個問題有困難。rescue_from NoMethodError

試圖做一個

rescue_from NoMethodError, :with => :try_some_options 

但它不工作。

編輯: 爲了測試我做一個簡單的重定向

def try_some_options 
redirect_to root_url 
end 

組織編寫了:我的控制器的樣品 。按照下面的建議添加(例外)。

我知道我得到錯誤的原因。使用Authlogic和authlogic_facebook_connect插件。當從facebook插件創建用戶時,與用戶關聯的「MyCar」模型不像通常在用戶在本地註冊時創建的那樣創建。由於我確實需要調用用戶模型並在用戶網站的不同部分引用用戶的汽車,因此我希望執行類似於以下所示的內容,並最終將其放入我的application_controller中。

class UsersController < ApplicationController 
before_filter :login_required, :except => [:new, :create] 
rescue_from NoMethodError, :with => :try_some_options 

... 

def show 
    store_target_location 
    @user = current_user 
    end 

def create 
    @user = User.new(params[:user]) 
    if @user.save 
    MyCar.create!(:user => @user) 
    flash[:notice] = "Successfully created profile." 
    redirect_to profile_path 
    else 
    render :action => 'new' 
    end 
end 
... 

protected 

def try_some_options(exception) 
    if logged_in? && current_user.my_car.blank? 
     MyCar.create!(:user => current_user) 
     redirect_to_target_or_default profile_path 
    end 
end 
... 
end 

EDITED 3:黑客攻擊了,因爲現在我知道爲什麼錯誤顯示出來,而是想弄清楚如何rescue_from NoMethodError

class UsersController < ApplicationController 
before_filter :login_required, :except => [:new, :create] 
before_filter :add_car_if_missing 

def add_car_if_missing 
    if logged_in? && current_user.my_car.blank? 
    MyCar.create!(:user => current_user) 
    end 
end 
end 
+0

你能否解釋一下你的意思是「它不工作」? – mportiz08 2010-09-03 00:44:41

+0

它不會觸發「try_some_options」方法。 – pcasa 2010-09-03 01:12:56

+0

代碼看起來像觸發這個異常的地方是什麼? – 2010-09-03 02:10:13

回答

6

我試圖來時只是看了你的帖子解決同樣的問題。最後我做了以下幾點:

class ExampleController < ApplicationController 
    rescue_from Exception, :with => :render_404 
    ... 

private 

    def render_404(exception = nil) 
    logger.info "Exception, redirecting: #{exception.message}" if exception 
    render(:action => :index) 
    end 
end 

這對我很好。這是一個抓住所有情況,但它可能會幫助你。祝一切順利。