新手在这里尝试使用role_model和CanCan启动和运行。我已将两个 gem 添加到我的 Gemfile 中。设置它们并可以验证它们是否确实在工作。但是,当我尝试在我的 Dev DB 中向用户添加新角色时,rails 控制台会回滚并且什么都不保存?我被难住了,因为我认为这将是小菜一碟......
这是我的代码:
模型 - User.rb
class User < ActiveRecord::Base
include RoleModel
attr_accessible :email, :username, :roles, :password, :password_confirmation
has_secure_password
validates :email, :username, :password, presence: true
validates :email, :username, uniqueness: true
roles :admin, :moderator, :developer, :user
end
模型 - 能力.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
user.can :manage, :all if user.is? :admin
end
end
我在 Rails 控制台上运行的命令为用户添加正确的角色:
admin_user = User.find(1)
admin_user.roles = [:admin]
admin_user.save
然后 Rails 吐出:
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE ("users"."email" = 'admin_user@example.com' AND "users"."id" != 1) LIMIT 1
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE ("users"."username" = 'admin_user' AND "users"."id" != 1) LIMIT 1
(0.1ms) ROLLBACK
=> false