且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

扶手:使用惨惨定义多个角色,这取决于单一模型的实例?

更新时间:2023-09-20 17:42:04

我遇到了一个同样的需求今天发现了一个办法做到这一点上的惨惨维基

I ran into a same needs today and found a way to do this on CanCan Wiki.

简单遵循这些简单的步骤:

Simple follow these simple steps:

1)与你的角色名创建User类下一个常数:

1) Create a constant under the User class with your role names:

class User < ActiveRecord::Base
  ROLES = %w[admin moderator author banned]
end

2A)创建,如果你正在使用的ActiveRecord运行迁移:

2a) Create and run a migration if you are using ActiveRecord:

rails generate migration add_roles_mask_to_users roles_mask:integer
rake db:migrate

2B)上的用户模型添加这些领域,如果你使用的是Mongoid:

2b) Add these field on User model if you are using Mongoid:

field :roles_mask, type: Integer

3)下一步,你需要以下code添加到用户模式:

3) Next you'll need to add the following code to the User model:

# in models/user.rb
def roles=(roles)
  self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end

def roles
  ROLES.reject do |r|
    ((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
  end
end

4)如果你使用的设计没有强有力的参数,不要忘了添加attr_accessible:角色对你的用户模型。如果您使用的是与strong_parameters设计,无论是作为在Rails 3应用程序宝石,或者是内置在Rails中4,不要忘记给角色添加到允许列表中的控制器:

4) If you're using devise without strong parameters, don't forget to add attr_accessible :roles to you user model. If you're using devise with strong_parameters, either as a gem in a Rails 3 app, or as is built-in in Rails 4, dont forget to add the roles to the permitted list in the controller:

class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :password_confirmation, roles: [])}
  end
end

5)增加code波纹管生成视图中的复选框来设置这些角色:

5) Add the code bellow to generate checkboxes in the view for setting these roles:

<% for role in User::ROLES %>
  <%= check_box_tag "user[roles][#{role}]", role, @user.roles.include?(role), {:name => "user[roles][]"}%>
  <%= label_tag "user_roles_#{role}", role.humanize %><br />
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>

6)最后,你可以再增加一个方便的方法来检查能力类用户的角色:

6) Finally, you can then add a convenient way to check the user's roles in the Ability class:

# in models/user.rb
def is?(role)
  roles.include?(role.to_s)
end

# in models/ability.rb
can :manage, :all if user.is? :admin

这就是它。

我希望这可以帮助。