简体   繁体   中英

current_user defined in application.rb will not work in create action

This is from my 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

And this is a create method from my 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

When called it says:

undefined method `login' for nil:NilClass

What could be stopping current_user from being found?

current_user is found correctly. If not, there would be a NoMethodError .

In your case current_user is simply returning nil . Then you try to use .login on nil which leads to the error you see:

undefined method `login' for nil:NilClass

So try to find out why current_user returns nil in your create action. Maybe because it can happen that the session[:user_id] is not set or no user is found?


Based on the comments the problem is the CSRF protection. Because of the CSRF error, the session is not initialized in create and therefore current_user is blank.

CSRF protection is usually enabled in ApplicationController :

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

You should find out why CSRF protection kicks in and fix it. Disabling it makes your site insecure. Take a look at the ruby security guide about CSRF .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM