简体   繁体   English

在Rails中为登录用户显示不同的菜单项

[英]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 ) 我试图在Rails应用程序中创建一个菜单栏,以在用户未登录时显示“ Login ,并显示“ Logout以及他们可以使用的操作,例如AdminUsers等。我试图在我的代码中使用此代码。应用程序布局( app/views/layout application.html.haml

%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? 除了菜单本身之外,我不需要更改布局中的任何内容,因此我不想根据用户是否登录来呈现不同的布局。是否可以显示logged_in? method to the application layout, or somehow let the layout know if a user is logged in? application布局的方法,或者以某种方式让布局知道用户是否已登录?

Assuming you're using Devise for authentification, the correct method is user_signed_in? 假设您使用Devise进行身份验证,正确的方法是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 在您的ApplicationController中

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 现在,在您的视图中,您可以像这样检查@logged_in是否为真

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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