Multi Role

第一种方式:gem rolify
rolify

第二种方式:
1.在model中定义角色,批准方式等

user.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
enum role: { :user, :vip, :admin }
after_initialize :set_default_role, if: :new_record?
def set_default_role
self.role ||= :user
end

def admin?
self.role == 'admin'
is_admin == true
end

def is_user?
self.role = 'user'
end

def vip?
self.role = 'vip'
is_vip == true
end

def qunlified_vip?
role == 'vip' && is_admin
end

def unqunlified_vip?
role == 'vip' && !is_admin
end

def approve!
self.is_admin = true
save
end
end

2.在注册界面加上角色选择按钮

devise/registration/new.rb
1
2
3
4
<%= f.radio_button(:role, "user") %>
<%= label(:role, "用户注册") %>&nbsp;&nbsp;&nbsp;&nbsp;
<%= f.radio_button(:role, "vip") %>
<%= label(:role, "商家注册") %>

3.在model中加上role,is_vip的栏位
rails g migration add_role_to_users

1
2
3
def change
add_column :users, :role, :string
end

rails g migration add_is_vip_to_user

1
2
3
def change
add_column :users, :is_vip, :boolean, default: false
end

4.新建一个controller定义index,批准,取消等方法

controller/admin/users_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    class Admin::UsersController < ApplicationController
before_action :authenticate_user!
before_action :require_is_admin
layout 'admin'
def index
@users = User.where(role:'vip').order('is_vip ASC')
end
def approve_vip
@user = User.find(params[:user_id])
@user.approve!
redirect_to :back
end

def cancel_vip
@user = User.find(params[:user_id])
@user.cancel!
redirect_to :back
end
end

5.在route中添加路径

config/routes.rb
1
2
3
4
5
6
namespace :admin do
resources :users do
post :approve_vip
post :cancel_vip
end
end

6.建立view页面,显示需要的界面

views/admin/user/index.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<div class="container body well">
<h3 class="text-center">会员管理</h3>
<br>
<br>
<table class="table table-responsive">
<thead>
<tr>
<th>用户id</th>
<th>用户邮箱</th>
<th>用户角色</th>
<th>状态</th>
<th>审批</th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.id %></td>
<td><%= user.email %></td>
<td><%= user.role %></td>
<td>
<% if user.qunlified_vip? %>
已通过审核
<% else %>
未通过审核
<% end %>
</td>
<td>
<% if user.unqunlified_vip? %>
<%= link_to("批准成为会员", admin_user_approve_vip_path(user),:method => :post)%>
<% else %>
<%= link_to("取消会员身份", admin_user_cancel_vip_path(user),:method => :post)%>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>

PS: 同一页面两个表格中显示两个不同的role