mardi 5 janvier 2016

Pundit Error with authorize @user in Rails 4 Application [Pundit::NotAuthorizedError in UsersController#destroy]

I am getting the following error while trying to delete a user in my Rails 4 App.

Pundit::NotAuthorizedError in UsersController#destroy
not allowed to destroy? this #<User:0x005595f691bd10>
Extracted source (around line #30):    
        @user = User.find(params[:id])
        # debugger
        authorize current_user
        @user.destroy
        redirect_to users_path, :notice => "User deleted."
     end

I am giving the User Controller bellow :

class UsersController < ApplicationController
    before_filter :authenticate_user!


    before_action :set_menu

    def index
        @users = User.all.page(params[:page]).per(8)
        authorize @users
    end

    def show
        @user = User.find(params[:id])
        authorize @user
  end

  def update
        @user = User.find(params[:id])
        #authorize @user
        if @user.update_attributes(secure_params)
          redirect_to users_path, :notice => "User updated."
        else
          redirect_to users_path, :alert => "Unable to update user."
        end
     end

     def destroy
        @user = User.find(params[:id])
        authorize @user
        @user.destroy
        redirect_to users_path, :notice => "User deleted."
     end

     private

     def secure_params
       params.require(:user).permit(:role)
     end

     def set_menu
        store_menu("User")
    end

end

The bellow is my User Model Code

class User < ActiveRecord::Base

  enum role: [:admin,:user]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :user
  end
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :customer
  # has_one :customer, dependent: :destroy
end

The bellow is my User policy file

class UserPolicy < ApplicationPolicy
  attr_reader :user, :model

  def initialize(user, model)
    @user = user
    @model = model
  end

  def index?
    @user.admin?
  end
  class Scope < Scope
    def resolve
      scope
    end
  end

end

How to resolve the error on delete or destroy action of a particular user ?

Aucun commentaire:

Enregistrer un commentaire