Cookie已签名 - 未定义方法'已签名'

时间:2018-03-05 16:13:08

标签: ruby-on-rails ruby-on-rails-5

在Application Controller中,如果cookies.signed [:user_id],我有一个方法current_user和if语句。该方法一直有效,但今天我创建了新的控制器和路由,它给我一个错误

undefined method `signed' for nil:NilClass

这是应用程序控制器:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session

  before_action :current_user

  protected
  def current_user
    if cookies.signed[:user_id] && User.find(cookies.signed[:user_id])
      @current_user = User.find(cookies.signed[:user_id])
    end
  end
end

这是服务器日志:

Processing by HomeController#index as HTML
Completed 500 Internal Server Error in 23ms (ActiveRecord: 0.0ms) 

NoMethodError (undefined method `signed' for nil:NilClass):

app/controllers/application_controller.rb:18:in `current_user'
  Rendering /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
  Rendering /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
  Rendered /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (4.5ms)
  Rendering /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
  Rendered /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)
  Rendering /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
  Rendered /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.3ms)
  Rendered /Users/Dudis/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (187.4ms)

为什么它不再起作用的任何建议?我没有在应用程序中进行任何更新。

2 个答案:

答案 0 :(得分:1)

从错误中可以看出,方法cookies返回nil。 AFAIK,rails&#39;即使您没有任何cookie,实施也不应该这样做。这让我觉得它不是轨道&#39;正在运行的版本。如果我猜测,你在该控制器中有一个方法cookies在评论中确认)。

答案 1 :(得分:0)

cookies为nil undefined method signed for nil:NilClass (nil.signed)