0
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :null_session

  rescue_from ActiveRecord::RecordNotFound, :with => record_not_found #spazzing out

  def record_not_found
    flash[:error] = 'Could not find specified role'
    redirect_to record_not_found_path
    true
  end

end

那怎么错了?当我尝试运行规范时,我得到:

in `<class:ApplicationController>': undefined local variable or method `record_not_found' for ApplicationController:Class (NameError)

我错过了什么吗

4

2 回答 2

2

在 , 的:with => record_not_found参数中rescue_from尚未record_not_found定义,因此它引发了错误。您应该提供一个符号,如:

rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

与http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from中的示例保持一致

于 2013-12-20T06:34:38.333 回答
-1

首先,recovery_from :with => 中接受的参数必须是字符串或符号

其次,您应该使用 protected 保护被调用的方法,以防止可能的错误使用

class ApplicationController < ActionController::Base

  protect_from_forgery with: :null_session
  # parameter for :with has to be a string or symbol 
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  # to prevent an external access
  protected

  def record_not_found
    flash[:error] = 'Could not find specified role'
    redirect_to record_not_found_path
    true
  end
end
于 2013-12-20T06:40:42.563 回答