新手在这里尝试使用role_model和CanCan启动并运行。我已将两个宝石添加到我的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
模型 - Ability.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
答案 0 :(得分:1)
看起来这与role_model无关。在纯新手方式中,我没有意识到我试图保存的用户遇到了我在User.rb中设置的“密码”验证。我删除了
:password, presence: true
来自该文件,因为我不确定是否有必要进行以前的验证。无论如何,问题在于需要修复错误。