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?
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 %>
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).
I found the solution, it appears that
user_logged_in?
Is not used anymore, and instead you need to use
user_signed_in?
So with the code you gave this should work:
<% if user_signed_in? %>
<%= render :partial => "home/statusbar" %>
<% end %>
This code rendered a partial for me.
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
There is an even shorter way to render your partial with a conditional
<%= render(partial: "home/statusbar") if current_user.present? %>
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.