application.rb中定义的current_user在create action中不起作用

时间:2015-11-13 19:04:46

标签: ruby-on-rails ruby-on-rails-4.1

这是来自我的application_controller.rb

 private

  def current_user
    return unless session[:user_id]
    @current_user ||= User.find_by_id(session[:user_id])
  end

  helper_method :current_user

这是我的comments_controller.rb

中的一个创建方法
def create

    @user = User.find(params[:user_id]) 
    @user.comments.create(:user_id => @user.id, :commenter => current_user.login, :body => params[:comment][:body])
    respond_to do |format| 
         format.js 
         format.html { redirect_to(@user, :notice => 'Comment was successfully created.') } 
     end
  end

当被叫时说:

nil的未定义方法`login':NilClass

什么可以阻止找到current_user?

1 个答案:

答案 0 :(得分:1)

找到

current_user正确无误。如果没有,则会有NoMethodError

在您的情况下,current_user只是返回nil。然后,您尝试在.login上使用nil,这会导致您看到的错误:

undefined method `login' for nil:NilClass

因此,请尝试找出current_user在您的创建操作中返回nil的原因。也许是因为没有设置session[:user_id]或者没有找到用户?

根据评论,问题是CSRF保护。由于CSRF错误,会话未在create中初始化,因此current_user为空。

CSRF保护通常在ApplicationController中启用:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

您应该了解为什么CSRF保护会启动并修复它。禁用它会使您的网站不安全。看看ruby security guide about CSRF

相关问题