Ruby on rails 使用Rolify定义角色
我正在尝试用Rails 4制作一个应用程序 我正在研究角色管理,并希望使用Rolify,因为它支持实例级别的角色分配 对于其他看同样问题的人,下面有两个非常好的答案(我只能勾选一个,但我同时使用了两个)。查看下面的lorefnon和Cyb3rDud3答案)。我还在想办法,但已经用数组(如lorefnon所示)和控制器/路由函数(如Cyb3rDud3所示)进行了迁移 让我完全困惑的是,RolifyGem的所有文档都使用控制台来定义角色 如何在代码中定义角色 董事会中的其他人提出了一些问题,暗示他们在db:seeds文件中定义了角色。我不想这样做,因为我想控制谁更严格地使用我的种子文件,而不是谁可以创建角色 你在哪里做的 所有的例子都显示它是从控制台完成的。我想定义一个角色列表,然后我想给角色权限(我想对这个部分使用pundit) 我有一个用户模型。我看到的另一个宝石是榜样。它要求您在用户模型中创建角色数组。很明显,你应该在Rolify中这样做——没有一个文档给出这一步Ruby on rails 使用Rolify定义角色,ruby-on-rails,roles,user-roles,rolify,Ruby On Rails,Roles,User Roles,Rolify,我正在尝试用Rails 4制作一个应用程序 我正在研究角色管理,并希望使用Rolify,因为它支持实例级别的角色分配 对于其他看同样问题的人,下面有两个非常好的答案(我只能勾选一个,但我同时使用了两个)。查看下面的lorefnon和Cyb3rDud3答案)。我还在想办法,但已经用数组(如lorefnon所示)和控制器/路由函数(如Cyb3rDud3所示)进行了迁移 让我完全困惑的是,RolifyGem的所有文档都使用控制台来定义角色 如何在代码中定义角色 董事会中的其他人提出了一些问题,暗示他们
在哪里定义角色?在阅读了项目页面中的文档和示例后,我决定不使用gem来管理页面中的角色,因为我认为配置和使用gem会花费很多时间。因此,我做了以下工作(我相信您使用Desive作为您的用户模型,尽管它不是强制性的): 如果您想定义某些角色,并且“静态”不可修改但可从页面分配,请参见下文,如果不想,请跳到下一个粗体行
role:integer
的字段添加到User
模型中。(我们使用整数,因为该值将与我们在下一步中定义的枚举中的一个条目相关联)user.rb
(模型)中,添加一个enum
,如下所示:
class User < ActiveRecord::Base
devise :registerable, #...
enum role: [:admin, :normal, :premium, :moreRolesHere ]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :normal
end
end
#see if the current user is admin
if current_user.role == "admin"
#do some admin stuff
end
Role
的模型,其中包含一个字段Role:string
roles\u controller.rb
角色\u id:text
(这是文本,因为您需要在其中保存多个角色,所有角色包装在一个数组中),该列将表示他的角色。在user.rb
模型中,您可以使用get_roles
和其他def
s方法在控制器和视图中使用更干净的代码:
class User < ActiveRecord::Base
devise :registerable, #...
serialize :role_ids
#will return you an array of roles-(strings) of the user
def get_roles
roles = []
role_ids.each do |role_id|
roles << Role.find(role_id).role
end
return roles
end
#ask if this user has some role-(string)
def has_role(role)
roles = get_roles
return roles.include?(role)
end
end
class用户
Rolify文档不使用控制台定义角色-它演示了如何在纯ruby中添加角色。这是惊人的强大,因为你可以
定义可以运行ruby的角色。您不局限于某个配置文件或某个数据库表中定义的静态角色列表
您需要问的第一个问题是什么时候创建角色
最常见的用例分为两组:
1。角色是静态的。
应用程序开发人员、支持人员或公司主管在应用程序安装/部署期间以及在运行应用程序的生命周期内创建一次角色。这些预先创建的角色分配给不同的用户
此类角色最常见的用例包括公司人员(开发人员、经理、支持人员等)的建模指定,或主要已知职责(编辑、管理员、观众等)的建模
如果您的角色确实属于这样的用例,那么接下来您必须决定——谁负责创建和修改角色。通常有两种可能性:
1.1.应用程序开发人员自己是必须添加/删除/修改角色的人。在这种情况下,最好依靠种子数据或Rails迁移
迁移的优点是,您可以在需要时轻松回滚数据。此迁移是rolify Generator生成的迁移的补充,rolify Generator为您创建角色相关表的架构(请参阅下图)
这种迁移可能看起来像:
db/migrate/20151204083556_创建_应用程序_角色.rb
class CreateApplicationRoles < ActiveRecord::Migration
def up
['admin', 'support', 'editor'].each do |role_name|
Role.create! name: role_name
end
end
def down
Role.where(name: ['admin', 'support', 'editor']).destroy_all
end
end
class CreateApplicationRoles
有些人认为模式ch是一种反模式
class CreateApplicationRoles < ActiveRecord::Migration
def up
['admin', 'support', 'editor'].each do |role_name|
Role.create! name: role_name
end
end
def down
Role.where(name: ['admin', 'support', 'editor']).destroy_all
end
end
#Seeding the Role table
#
p "Removing existing #{Role.all.count} roles"
Role.destroy_all
p "Creating 7 roles"
[:user, :admin, :portfolio_manager, :programme_manager, :project_manager, :coordinator, :pmo].each do |role|
Role.create( name: role )
end
p "Should have created 7 Roles, roles created: #{Role.all.count}"
users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update]
def index
@users = User.all
end
def show
end
def edit
end
def update
respond_to do |format|
if @user.update(user_params)
# TODO: Move hardcode flash message into language file
format.html { redirect_to @user, notice: 'User was successfully updated.'}
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:username, :email, {role_ids: []})
end
end
routes.rb
Rails.appliction.routes.draw do
devise_for :users
root 'pages#home'
resources :users #must be after devise
end
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
user_unlock POST /users/unlock(.:format) devise/unlocks#create
new_user_unlock GET /users/unlock/new(.:format) devise/unlocks#new
GET /users/unlock(.:format) devise/unlocks#show
root GET / pages#home
about GET /about(.:format) pages#about
contact GET /contact(.:format) pages#about
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
index.html.erb
<!-- TODO: Tidy up this file and make it look good -->
<!-- TODO: Remove hard coded text to a locale file -->
<% @users.each do |user| %>
<p>
<%= link_to "#{user.username}<#{user.email}>", user %>
<%= link_to "edit", edit_user_path(user) %>
</p>
<% end %>
show.html.erb
<!-- TODO: Tidy up this file and make it look good -->
<!-- TODO: Remove hard coded text to a locale file -->
<p>
Username: <%= @user.username %>
</p>
<p>
Email address: <%= @user.email %>
</p>
<%= link_to "Back", users_path %>
edit.html.erb
<!-- TODO: Tidy up this file and make it look good -->
<!-- TODO: Remove hard coded text to a locale file -->
<p>
Username: <%= @user.username %>
</p>
<p>
Email address: <%= @user.email %>
</p>
<%= form_for @user do |f| %>
<% Role.all.each do |role| %>
<%= check_box_tag "user[role_ids][]", role.id, @user.role_ids.include?(role.id) %>
<%= role.name %></br>
<% end %>
<%= f.submit %>
<% end %>
<%= link_to "Back", users_path %>
class CreateApplicationRoles < ActiveRecord::Migration
def up
['admin', 'support', 'editor'].each do |role_name|
Role.create! name: role_name
end
end
def down
Role.where(name: ['admin', 'support', 'editor']).destroy_all
end
end