Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3, only rendering partial if a user is logged in

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:

<% if user_logged_in? %>
<%= render :partial => "home/statusbar" %>
<% end %>

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

<div id="status_bar">  
  Signed in as <%= link_to current_user.name, edit_user_registration_path %>
</div>

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?

like image 530
joseph Avatar asked Jul 21 '11 23:07

joseph


3 Answers

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

<% if current_user.present? %>
  <%= render :partial => "home/statusbar" %>
<% end %>
like image 62
Dave A-R Avatar answered Nov 20 '22 11:11

Dave A-R


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:

<% puts user_logged_in?.inspect %>
<% puts user_signed_in?.inspect %>

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).

like image 4
Brett Bender Avatar answered Nov 20 '22 12:11

Brett Bender


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

<% if false %>
  <%= render :partial => "home/statusbar" %>
<% end %>

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

<% if current_user %>
  <%= render :partial => "home/statusbar" %>
<% end %>

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

like image 1
loosecannon Avatar answered Nov 20 '22 11:11

loosecannon