ruby-on-railsrubydevisecancan

uninitialized constant Ability Rails


I have gone through different solutions given to this problem but none of them is working so please don't try to close the question as duplicate.

I have role column in my users table. So user can by admin or user and I need to put permissions on the base of user Role using CanCan. I want to give all permissions to admin. I am logged in as admin but when I access /users I get the error uninitialized constant Ability and when I remove load_and_authorize_resource my cancan permission doesn't work.My ability class looks like

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

In my UsersController I am having

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

And my routes file looks like

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

Solution

  • You are seeing uninitialized constant Ability because the load_and_authorize_resource method in your UsersController expects to find an Ability class.

    The solution is to move the file containing your ability definitions to 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