nikolay
nikolay

Reputation: 112

Rails - undefined method `admin' for nil:NilClass in Sessions#create

When I'm trying to login I'm getting:

undefined method `admin' for nil:NilClass

which is called from the layouts/_head.html.erb partial

_head.html.erb:

<% if session[:user_id] %>
  <% if @current_user.admin %>
    <%= button_to 'Swap to user', to_user_path(User.find_by(id: session[:user_id]).id), method: :put,
                    class: 'btn btn-warning' %>
  <% else %>
    <%= button_to 'Swap to admin', to_admin_path(User.find_by(id: session[:user_id]).id), method: :put,
                    class: 'btn btn-warning' %>
  <% end %>
<% end %>

As you can see, session[:user_id] exists. Here is application_controller.rb:

class ApplicationController < ActionController::Base
  before_action :set_user
  protect_from_forgery with: :exception

  def set_user
    if session[:user_id]
      @current_user = User.find_by(session[:user_id])
    end
  end
end 

Also the login button works through Ajax. So why am I getting @current_user as nil, if it's defines before_action in the application controller? (Remember: session[:user_id] != nil)

Upvotes: 0

Views: 67

Answers (2)

Mischa
Mischa

Reputation: 43298

Your use of find_by is incorrect. It should be:

@current_user = User.find_by(:id => session[:user_id])

Upvotes: 1

nikolay
nikolay

Reputation: 112

So the solve is to define @current_user in create method,like

def create
user = User.find_by(name: params[:name])
  respond_to do |format|
    if user and user.authenticate(params[:password])
       session[:user_id] = user.id
       @current_user = user
       format.js { }
    else
       format.js {flash.now[:notice] = 'Wrong pass/name'}
    end
  end
end

guesss its not absolute right,but one of possible method

Upvotes: 0

Related Questions