繁体   English   中英

Ruby on Rails,无法让cancan工作

[英]Ruby on Rails, can't get cancan to work

我一直在努力让康康整天工作。 我已经开始使用不同的教程多次,但是我仍然遇到相同的错误。

很简单,我有一个用户帐户(使用Devise创建),该帐户可以具有一个角色,即Admin或User。 这是能力等级:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.role? :admin
      can :manage, :all
    end
  end
end

在概要文件控制器中,我有一行load_and_authorize_resource ,类User包含ROLES = %w[admin user] http://localhost:3000/profiles/给我错误

app/models/ability.rb:6:in initialize'中wrong number of arguments (2 for 1)

使用替代方法user.admin?

undefined method `admin?' for #<User:0x5b34c10>

谷歌搜索上面的错误给出了很多结果,所以我不是唯一遇到此问题的人,但是没有一个解决方案对我有用。

是的,我已经将角色列添加到用户表中

class AddRoleToUsers < ActiveRecord::Migration
  def change
    add_column :users, :role, :string
  end
end

添加Gem,运行捆绑安装并重新启动服务器。

如果您具有以下条件,则该方法应该起作用:

能力

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new # guest user
   # raise user.role?(:administrator).inspect
    if user.role? :administrator

      can :manage, :all
      can :manage, User

    elsif user.role? :user
      can :read, :all

    end

  end
end

RoleUser.rb

class RoleUser < ActiveRecord::Base
  # attr_accessible :title, :body
  belongs_to :user
  belongs_to :role

end

角色

class Role < ActiveRecord::Base
  attr_accessible :name

  has_and_belongs_to_many :users
end

User.rb

 class User < ActiveRecord::Base

 has_and_belongs_to_many :roles

  def role?(role)
    self.roles.find_by_name(role.to_s.camelize)
  end

在定义角色,查找角色,将角色转换为字符串并将其驼峰化时,需要使用此功能。

seed.rb

%w(Employee Administrator).each { |role| Role.create!(:name => role)}

创建一个数组UserAdministrator

如果您正确地遵循了这些步骤,就可以正常工作。 并确保您具有以下迁移:

class UsersHaveAndBelongsToManyRoles < 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

那么您认为应该使用can? 通过做类似的事情

<% if can? :manage, User %> 
  .......
    ....
  ...
<% end %> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM