Rails 3, only rendering partial if a user is logged in-Collection of common programming errors

On a Rails 3.1 app, I have a method called user_logged_in? from Devise, which I want to use to render a partial selectively. Here’s the code in layouts/application.html.erb:


 "home/statusbar" %>

It uses a partial from a different controller. This is the partial:

  
  Signed in as 

An error occurs at current_user.name (undefined method), because current_user is nil. I could move the user_logged_in? check inside the partial, but I think it would be marginally more efficient if it were in the view.

Could you direct me to what the best practices are, or how I can overcome the undefined method error? Is it normal that Rails checks the code of the template even though it’s in an if block that fails?

  1. It looks like user_logged_in? is where something is going wrong.Does it work if you change to this?

    
       "home/statusbar" %>
    
    
  2. I’m familiar with Devise, but not the user_logged_in? method – did you define it yourself? The normal helper used in views is user_signed_in?. Also, try something like the following:

    
    
    

    Above the if statement in your view, and check your logs to make sure your call is returning false correctly (user_signed_in? should also be returning false). You should not be getting a nil error in that partial unless it is actually being rendered (meaning the code entered the if statement).

  3. That code is being run, ruby is duck typed and dynamic, all checks are at runtime. So you need to check your conditional . Try

    
       "home/statusbar" %>
    
    

    and see if it stll fails. A bettter solution would be

    
       "home/statusbar" %>
    
    

    I am unfamiliar with devise but this should work Since current user wil be nil if nobody is logged in

Originally posted 2013-11-09 22:58:49.