Show and hide based on user role in rails
Asked Answered
N

1

0

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?

Narwhal answered 28/12, 2012 at 22:14 Comment(0)
C
0

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.

Catamount answered 30/12, 2012 at 9:2 Comment(2)
Hi, will that also work with an approach where Seekers and Users have different views ?? rather then just a simple home.html.erb page? -Thanks!Narwhal
Because you can access user_signed_in? && current_user from any view, you will be able to check in any view wither the current_user is a seeker or not .. remember that its one User model, used in all your app, did you check the easy role gem?Catamount

© 2022 - 2024 — McMap. All rights reserved.