【问题标题】:rescue_from NoMethodErrorrescue_from NoMethodError
【发布时间】:2010-09-03 00:19:28
【问题描述】:

在解决这个问题时遇到了问题。

尝试做一个

rescue_from NoMethodError, :with => :try_some_options

但它不起作用。

编辑: 为了测试,我正在做一个简单的重定向

def try_some_options
 redirect_to root_url
end

编辑 2: 我的控制器示例。按以下建议添加(例外)。

我知道我收到错误的原因。使用 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:暂时破解它,因为我知道错误出现的原因,但想弄清楚如何从 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

【问题讨论】:

  • 你能解释一下“它不工作”是什么意思吗?
  • 它没有触发“try_some_options”方法。
  • 触发此异常的代码是什么样的?
  • 您确定在 UsersController 中抛出了 NoMethodError 吗?也许您正在重定向到 NoMethodError 尚未获救的另一个控制器。
  • 我知道我在不同的部分中调用了用户和 user.my_car,但在“显示”中只引用了一次。这就是我现在专注的地方。

标签: ruby-on-rails ruby


【解决方案1】:

我刚刚阅读了您的帖子,试图找到解决同一问题的方法。最后我做了以下事情:

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

这对我来说效果很好。这是一个包罗万象的情况,但它可能会对您有所帮助。一切顺利。

【讨论】:

  • 这个!是最好的答案吗...即使是 9 年后!
猜你喜欢
  • 2013-10-12
  • 2011-07-12
  • 2016-08-29
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 2017-12-23
  • 2017-09-22
  • 1970-01-01
相关资源
最近更新 更多