开发者

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] 开发者_StackOverflow= 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.


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.


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


What helped me:

  • Define methods to use in the controller in helper files
  • Define methods to use in the view in the relevant model file

Example

Suppose you had this in user_helper.rb

def something
 2 + 2
end

simply move that code into

models/user.rb

and it will be accessible in the view without any further effort.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜