Show and hide based on user role in rails

大城市里の小女人 提交于 2019-12-25 08:48:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14076469/show-and-hide-based-on-user-role-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!