Reputation: 59
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?
Upvotes: 1
Views: 225
Reputation: 5807
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.
Upvotes: 1