Ruby on rails 如何从控制台向rails应用程序添加角色?坎坎,设计
我已经可以创建用户了,但是如何动态添加角色呢?从控制台还是使用管理规则?设计,坎坎。我是Rails的新手,但如果你能向我提出一些想法或材料,我会很高兴的 用户模型:Ruby on rails 如何从控制台向rails应用程序添加角色?坎坎,设计,ruby-on-rails,authentication,devise,cancan,Ruby On Rails,Authentication,Devise,Cancan,我已经可以创建用户了,但是如何动态添加角色呢?从控制台还是使用管理规则?设计,坎坎。我是Rails的新手,但如果你能向我提出一些想法或材料,我会很高兴的 用户模型: class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :data
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 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
classdeveliecCreateUsersfalse,:default=>
t、 字符串:加密密码,:null=>false,:default=>
t、 字符串:地址
t、 字符串:城市
t、 字符串:state
t、 字符串:国家
t、 字符串:zip
##可恢复
t、 字符串:重置密码\u令牌
t、 日期时间:重置密码发送时间
##难忘的
t、 datetime:记住在
##可证实
#t.string:确认令牌
#t.datetime:已确认
#t.datetime:确认发送至
#t.string:未确认的电子邮件#仅当使用可再确认
##可锁
#t.integer:failed_尝试,:default=>0,:null=>false#仅当锁定策略为:failed_尝试时
#t.string:unlock_token#仅当解锁策略为:email或:两者皆有时
#t.datetime:locked_在
...
结束
结束
类CreateRolesfalse do | t|
t、 引用:角色,:用户
结束
结束
def自动关闭
drop\u表:角色\u用户
结束
结束
创建角色表需要迁移。之后
Role.create!(:name => 'admin')
在rails控制台中
Role.create!(:name => 'admin')