Saturday, April 30, 2016

Conditional partials with Devise gem



A common problem web developers face is the fact sometimes we need to show parts of a view only for logged (or non-logged) users. The most common situation is when you need to have a login button/link in your main page.

If you are using Devise gem for authentication this turns out to be a very simple matter. You just have to use the devise helper user_signed_in?. This helper returns true if there is a logged user and false otherwise. It may be used in your controllers, model or views.


In a view you may have something like

<% if user_signed_in? %>
    <%= render 'your_conditional_partial_name' %>
<% end %>

By the way... I know this is a bit off-topic for this post, but since we are talking about views and about embedded Ruby code, let me say a few words about a common confusion.

This week I saw a question at StackOverflow (unfortunately  I haven't the link right now) where a guy was presenting a common problem. He wrote in one of his views something like:

<%= @users.each |user| do %>
    # Some code to show user's fields
<% end %>

And he was complaining that after the user data his view was showing a Hash with all the values of the records.

The point here is that he used <%= %>, with the =, instead of only <% %> in his block opening. Ruby interpreted this as a request to show the contents of the variable inside the tags. So, I give you a free advise: Don't use the = in conditionals or block opening statements. This is one of those errors easy to do and hard to find.