Ruby on Rails,无法让cancan工作

时间:2013-02-25 17:25:05

标签: ruby-on-rails cancan

我一直试图让cancan整天工作。我已经多次使用不同的教程开始了,但我一直遇到同样的错误。

这很简单,我有用户帐户(使用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,用户类包含ROLES = %w[admin user]。转到http://localhost:3000/profiles/会给我错误

wrong number of arguments (2 for 1)初始化'`

中的

app/models/ability.rb:6:in

使用替代方法user.admin?给出

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

谷歌上面的错误给出了很多结果,所以我不是唯一有这个问题的人,但没有一个解决方案适合我。

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

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

添加了Gem,运行了bundle install并重新启动了服务器。

1 个答案:

答案 0 :(得分:0)

如果你有以下这个应该工作:

Ability.rb

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

您需要这样做,因为您正在定义角色,找到角色,将角色转换为字符串并将角色化。

<强> seeds.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 %>