CanCan独立角色模型

nat*_*han 3 devise cancan ruby-on-rails-3

我一直在关注CanCan中的单独角色模型实现的指南.当a ,尝试注册时,在创建时会抛出此错误.UserAssignment

User(#21477600) expected, got Symbol(#5785720)

我正在使用User通过以下before_save功能生成的Devise

class User < ActiveRecord::Base
.
.
.
 def create_profile
    profile = Profile.new :user_id => :id
  end

  def create_role
     Assignment.new :user => :id, :role => Role.find_by_role("user").id
  end
end
Run Code Online (Sandbox Code Playgroud)

我想将用户的角色默认为"用户",但我显然做错了什么.该如何实施?

ard*_*vis 9

不确定你是否看过这个,但Ryan Bates制作了一篇关于以下内容的精彩文件:

单独的角色模型

编辑:

这是我目前正在使用的.我相信你的'作业'与我的'UserRole'相同.

user.rb

#--
# Relationship
has_many :user_roles, :dependent => :destroy, :uniq => true
has_many :roles, :through => :user_roles, :uniq => true

#--
# Instance Method

# Determine if the user has a specified role
# You can find this method at: https://github.com/ryanb/cancan/wiki/Separate-Role-Model
# Written by Ryan Bates, I added the downcase though to detect 'Admin' vs 'admin'.
# Example:
#       user.has_role? :Admin
#       => true
def has_role?(role_sym)
  roles.any? { |role| role.name.underscore.to_sym == role_sym.downcase }
end
Run Code Online (Sandbox Code Playgroud)

role.rb

#  id         :integer(4)      not null, primary key
#  name       :string(255)  

#--
# Relationship
has_many :user_roles, :dependent => :destroy, :uniq => true
has_many :users, :through => :user_roles, :uniq => true
Run Code Online (Sandbox Code Playgroud)

user_role.rb

#  id         :integer(4)      not null, primary key
#  user_id    :integer(4)
#  role_id    :integer(4)

#--
# Relationship
belongs_to :user
belongs_to :role
Run Code Online (Sandbox Code Playgroud)

然后在我的能力.rb

def initialize(user)
  user ||= User.new                   # in case of a guest
  if user.has_role? :Admin            # The user is an Administrator
    can :manage, :all
  else
    can :read, :all
  end
end
Run Code Online (Sandbox Code Playgroud)

然后,我可以通过执行以下操作轻松地分配角色,例如在我的种子文件中:

# Create Users
...

# Roles
admin = Role.create!(:name => "admin")
standard = Role.create!(:name => "standard")

# UserRoles :Admin
user1.roles << admin
user2.roles << standard
Run Code Online (Sandbox Code Playgroud)

因此,通过调用user.roles << [role_name],我实际上创建了一个UserRole,它具有user_id和role_id.