Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 643
geeky_monster Avatar asked Jun 04 '11 21:06

geeky_monster


2 Answers

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.

like image 54
Jeremy Weathers Avatar answered Nov 14 '22 01:11

Jeremy Weathers


Generally you should have methods like current_user defined in your application_controller and then make them available as helpers in the views. This way the controllers have access to them (and trust me, you will most likely need access to things like that). Example:

def current_user
  ..
end
helper :current_user
like image 27
Jits Avatar answered Nov 14 '22 00:11

Jits