简体   繁体   中英

Show different menu items for logged in user in Rails

I am attempting to create a menu-bar in my Rails application to show Login when a user is not logged in, and Logout plus what actions they have available to them, ie Admin , Users , etc. I attempted to use this code in my application layout ( application.html.haml in app/views/layout )

%ul{:class => 'nav'}
%li= link_to 'Home', :root
    - if logged_in?
        %li= link_to 'Logout', logout_url

However, it gives me an error stating,

NoMethodError in Session#new
undefined method `logged_in?' for #<#<Class:0x007f771bbe0f70>:0x007f771bc6a1a8>

I don't need to change anything in the layout other than the menu itself, so I don't want to render different layouts depending on if a user is logged in. Is it possible to show the logged_in? method to the application layout, or somehow let the layout know if a user is logged in?

Assuming you're using Devise for authentification, the correct method is user_signed_in?

Edit :

Controller methods can only be called from controllers. However, you could store the result of that method in an instance variable. In your ApplicationController do

before_filter :login_check

def login_check
  @logged_in = logged_in?
end

Now in your view you can check if @logged_in is true, like this

%ul{:class => 'nav'}
%li= link_to 'Home', :root
    - if @logged_in
        %li= link_to 'Logout', logout_url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM