未初始化的常量Ability Rails

时间:2014-12-16 12:05:30

标签: ruby-on-rails ruby devise cancan

我已经针对这个问题找到了不同的解决方案但是没有一个能够解决这个问题,所以请不要试图将问题视为重复。

我的用户表中有角色列。因此,用户可以adminuser,我需要使用CanCan将权限放在用户角色的基础上。我想向管理员授予所有权限。我以管理员身份登录但是当我访问/users时收到错误uninitialized constant Ability,当我删除load_and_authorize_resource时,我的cancan权限无效。我的能力类似乎

class Ability
  include CanCan::Ability

  def initialize(user)
    #abort("Message goes here")
    user ||= User.new # guest user
    #abort('some user')
    if user.role == 'admin'
      can :manage, :all
    elsif user.role == 'user'
      can :manage, Micropost do |micropost|
        micropost.try(:owner) == user
      end
      can :update, User do |users|
        users.try(:owner) == user
      end
    else
     can :read, :all
    end
  end
end

在我的UsersController我有

class UsersController < ApplicationController
  load_and_authorize_resource
  #devise code
  before_filter :authenticate_user!, only: [:index, :edit, :update, :destroy, :following, :followers]
  blah blah
 end

我的路线文件看起来像

FirstApp::Application.routes.draw do

  devise_for :users

  resources :users do
  member do
    get :following, :followers
  end
end
#resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]

root to: "static_pages#home"

match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
end

1 个答案:

答案 0 :(得分:2)

您看到uninitialized constant Ability,因为load_and_authorize_resource中的UsersController方法希望找到一个Ability类。

解决方案是将包含您的能力定义的文件移至app/models/ability.rb

#app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    #abort("Message goes here")
    user ||= User.new # guest user
    #abort('some user')
    if user.role == 'admin'
      can :manage, :all
    elsif user.role == 'user'
      can :manage, Micropost do |micropost|
        micropost.try(:owner) == user
      end
      can :update, User do |users|
        users.try(:owner) == user
      end
    else
     can :read, :all
    end
  end
end