Search code examples
ruby-on-railsruby-on-rails-3sessionhelpersession-cookies

Helper Class not Accessible from View


I defined a helper class as below

module SessionsHelper

  def current_user 
        @current_user= User.find_by_fbid(session[:fbid])
  end


  def sign_in(user)
        session[:fbid] = user.fbid
        @current_user = user

  end


  def signed_in?
       !current_user.nil?
  end


  end  

I included the Helper Class in my Application Controller

class ApplicationController < ActionController::Base
  protect_from_forgery
  include SessionsHelper


end

The sign in method gets called from Session Controller

class SessionsController < ApplicationController


  def create

  user = User.find_or_create_by_fbid(params[:user][:fbid]) 
  user.update_attributes(params[:user])
  sign_in(user)
  redirect_to user_path(user)

  end

end

However I am not able to access 'current_user' variable from users#show view.

 <% if signed_in? %>
<p>
  <b>Current User:</b>
  <%= current_user.name %>
</p>


<% end %>

It says : undefined method `name' for nil:NilClass

Can anyone please advise ? The method current_user does not get called at all from index.


Solution

  • Putting include SessionsHelper in your controller includes those module methods in the controller, so they are accessible in your controller methods. You want the helper methods available in your views, so you need to use helper SessionsHelper in your application controller.

    That being said, I do agree with Jits that the methods you have in SessionsHelper really do belong in the controller instead of in a helper.