简体   繁体   中英

Rails - Role based Views using Pundit

I am working on creating an app using Devise and Pundit to create users and assign them roles.

With that, I want to have role-based views in my app. I'm having a hard time thinking through how to make that possible.

When you login, if you're a user you should redirect to the user home view. If you're a manager you should redirect to a manager home view.

What's the best way, at a high level, to write that logic? Should it live in a controller, a view, perhaps utilize partials to keep things DRY....

Any tips are appreciated.

Take a look at the rolify gem for assigning and checking roles on users. In my limited experience it is pretty obvious where that logic goes, usually in the controller if you are going to redirect or render different views. Occasionally it's not unreasonable to put it in a view - for example, if you have a page listing a bunch of items that is the same for everyone, except that you want to show "delete" link next to each item only if the current user is an admin.

rolify - https://github.com/EppO/rolify

According to the Single Responsibility Principle , each object should do the smallest possible useful thing. For Rails controllers, that thing is handling requests and rendering views with associated objects. So I would put that in a controller.

Devise has a great wiki on the subject of redirecting after a successful login.

i met the same problem, what i did was

1- create role column in user table

2- create enum in user model as

enum role: [:Manager, :Developer, :Quality]

3- create three partials

  1. _manager.html.erb
  2. _developer.html.erb
  3. _quality.html.erb

4- create index.html.erb and put the following

<% if current_user.Manager? %>
<%= render "dashboard/manager" %>
<% elsif current_user.Developer?%>
<%= render  "dashboard/developer" %>
<% else %>
<%= render  "dashboard/quality" %>
<% end %>

thanks to: Multiple Devise Users with different dashboards

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM