救援_来自 NoMethodError [英] rescue_from NoMethodError

查看:32
本文介绍了救援_来自 NoMethodError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在解决这个问题时遇到问题.

Having problems figuring this out.

尝试做一个

rescue_from NoMethodError, :with => :try_some_options

但它不起作用.

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

EDITED: For testing I'm doing a simple redirect

def try_some_options
 redirect_to root_url
end

编辑 2:我的控制器示例.添加(例外)如下建议.

EDITED 2: Sample of my controller. Added (exception) as recommended below.

我知道我收到错误的原因.使用 Authlogic 和 authlogic_facebook_connect 插件.当用户从 facebook 插件创建时,与用户关联的MyCar"模型不会像通常创建的那样创建,如果用户在本地注册.由于我确实调用了用户模型并在网站的不同部分引用了用户汽车,因此我想做一些类似于您在下面看到的操作,并最终将其放入我的 application_controller 中.

I know the reason I'm getting the error. Using Authlogic and authlogic_facebook_connect plugin. When user is created from the facebook plugin the "MyCar" model, which is associated with a user is not created like it normally is created if a user registers locally. Since I do call on the user model and reference the users car throughout different parts of the site, I would like to do something like what you see below and eventually put it in my 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

已编辑 3:由于我知道为什么会出现错误,因此暂时对其进行了修改,但想弄清楚如何从 NoMethodError 中进行救援

EDITED 3: Hacked it for now since I know why the error is showing up, but would like to figure out how to 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

推荐答案

当我试图想出解决同一问题的解决方案时,我刚刚阅读了您的帖子.最后我做了以下事情:

I just read your post when trying to come up with a solution to the same problem. In the end I did the following:

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

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

This worked well for me. It is a catch all situation yet it just may help you. All the best.

这篇关于救援_来自 NoMethodError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆