ruby-on-railscontrollerrolescancan

Show and hide based on user role in rails


I have the following code in my home.html.erb file;

<!-- if seeker is logged in show button "Grab it" -->
<% if user_signed_in? %>
<div class="grabit alignright">
<small>want to work on this?</small>
<!-- if seeker is not logged in, show him the output text of "Sign in to work on this job" -->
<% else %>
<small>are you a guru? want to work on this? Sign up.</small>
<% end %>
</div>

Now as you can see I'm trying to have Seeker as a user role. Depending if that type of user with that type of role is signed in or not, different content is shown.

I have Devise + CanCan installed. Now very new to this and I've looked all over to see how to do this. I will have "Users" with normal roles of users and "Seekers" with seeker role. Using the above code only shows when a user is signed in, but not a seeker.

Is it as simple as seekers_signed_in? that I should be using? compare to user_signed_in? I've generated the Devise views for both Users and Seekers and Admins. Admins will be able to delete, update, etc. for users and seekers. Users post items and Seekers grab them.

Can anyone help?


Solution

  • You don't have to create Users& Seekers (two devise models), instead you can create only one model as common and call it User, then add as many roles as you need.

    I recommend using this gem for easy roles configuration,

    Then in your home.html.erb you simply do the following:

    <!-- if seeker is logged in show button "Grab it" -->
    <% if user_signed_in? && current_user.is_seeker? %>
    <div class="grabit alignright">
    <small>want to work on this?</small>
    <!-- if seeker is not logged in, show him the output text of "Sign in to work on this job" -->
    <% else if !user_signed_in?%>
    <small>are you a guru? want to work on this? Sign up.</small>
    <% else%>
    <small>You are not a seeker, you need to be a seeker!</small>
    <% end %>
    </div>
    

    CanCan is used at Controller level, so the above approach is easy and direct for your case.

    I hope this will help.