如何为CanCan设置角色,以及如何将这些角色分配给用户?我希望至少在注册时有一个下拉菜单供用户选择他们的角色。我不确定所有的文档是否都包含了这个信息,但任何帮助都将不胜感激!
如何为CanCan设置角色,以及如何将这些角色分配给用户?我希望至少在注册时有一个下拉菜单供用户选择他们的角色。我不确定所有的文档是否都包含了这个信息,但任何帮助都将不胜感激!
User#has_role?
来检查关联。# file: app/models/user.rb
class User < ActiveRecord::Base
has_many :user_roles, :dependent => :destroy
has_many :roles, :through => :user_roles
def has_role?(name)
roles.pluck(:name).member?(name.to_s)
end
end
# file: app/models/role.rb
class Role < ActiveRecord::Base
has_many :user_roles, :dependent => :destroy
has_many :users, :through => :user_roles
end
# file: app/models/user_role.rb
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
# file: db/migrate/xxx_create_users.rb
class CreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :email, :null => false, :default => ""
# ... any other fields you want ...
t.timestamps
end
end
end
# file: db/migrate/xxx_create_roles.rb
class CreateRoles < ActiveRecord::Migration
def change
create_table :roles do |t|
t.string :name
t.timestamps
end
end
end
# file: db/migrate/xxx_create_user_roles.rb
class CreateUserRoles < ActiveRecord::Migration
def change
create_table :user_roles do |t|
t.references :user
t.references :role
t.timestamps
end
add_index :user_roles, [:user_id, :role_id], :unique => true
end
end
现在,您的能力文件看起来大致如下:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # support guest user
if user.has_role?(:admin)
can :manage, :all
elsif user.has_role?(:nsa)
can :read, :all
elsif user.has_role?(:editor)
# ... add other abilities here
end
end
end
需要明确的是,这并没有回答原帖中如何创建角色的问题。但由于用户、角色和用户角色现在都是完整的Rails模型,您可以使用标准的CRUD工具来管理它们。但90%的时间,您只需要将管理员权限分配给一两个用户,在种子文件中轻松完成,像这样:
# file: db/seeds.rb
# create a role named "admin"
admin_role = Role.create!(:name => "admin")
# create an admin user
admin_user = User.create!(:email => "admin@admin.com")
# assign the admin role to the admin user. (This bit of rails
# magic creates a user_role record in the database.)
admin_user.roles << admin_role
我大部分都弄清楚了。
比如:
if user.has_role? :admin
can :manage, :all
else
can :read, :all
end
这基本上是“设置”管理员角色。出于某种原因,我认为你还需要在其他地方初始化该角色。
To assign the roles, following most tutorials I've seen, you need to go into the rails console and use something similar to:
user = User.find(1)
user.add_role :admin # sets a global role
user.has_role? :admin
=> true