我可以创建用户,但是如何动态添加角色?从控制台或管理规则?设计,CanCan。我是Rails的新人,但如果你能给我一些想法或材料,我会很高兴。
用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable #:trackable, :validatable
has_and_belongs_to_many :roles
def role?(role)
return !!self.roles.find_by_name(role)
end
end
能力等级
class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
user ||= User.new # guest user (not logged in)
if user.role? :admin
can :manage, :all
elsif user.role? :editor
can :edit, :all
else
can :read, :all
end
end
end
角色模型
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
迁移
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :login
t.string :full_name
t.date :birthday
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
t.string :address
t.string :city
t.string :state
t.string :country
t.string :zip
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
...
end
end
class CreateRoles < ActiveRecord::Migration
def change
create_table :roles do |t|
t.string :name
t.timestamps
end
end
end
class UsersHaveAndBelongToManyRoles < ActiveRecord::Migration
def self.up
create_table :roles_users, :id => false do |t|
t.references :role, :user
end
end
def self.down
drop_table :roles_users
end
end
答案 0 :(得分:2)
您需要迁移才能创建角色表。之后
Role.create!(:name => 'admin')
在rails console中