'how to handle authorize! :update, @post ArgumentError in rails cancancan gem
I want to grant all permission to admin, and only read permission to normal user. so, after hitting /posts/1/edit for admin its working fine, but for normal user its giving
ArgumentError in PostsController#edit
wrong number of arguments (given 2, expected 0..1)
Application_Controller.rb
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protect_from_forgery with: :exception
rescue_from CanCan::AccessDenied do
flash[:error] = 'Access denied!'
redirect_to root_url
end
protected
def configure_permitted_parameters
added_attrs = [:first_name, :last_name, :phone, :gender, :username, :email, :password, :password_confirmation, :remember_me]
devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
devise_parameter_sanitizer.permit :sign_in, keys: [:login, :password]
devise_parameter_sanitizer.permit :account_update, keys: added_attrs
end
end
Post_controller.rb
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :fetch_all_posts_and_users
#some code
def edit
@post = Post.find(params[:id])
authorize! :update, @post
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to(post_path(@post))
else
render('edit')
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
end
private
def post_params
params.require(:post).permit(:title, :image, :total_likes)
end
def fetch_all_posts_and_users
@posts = Post.all
@users = User.all
end
end
I had also add load_and_authorize_resource but its not working for both admin and normal user
Ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
else
can :read, :all
end
end
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
