0

I'm trying to add authorization to my rails app and want to redirect a non-user to root_url when they try to access posts/new, using rescue_from. However, there is no redirect to root or error message being displayed and I'm not sure why.

This is my application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  rescue_from Pundit::NotAuthorizedError do |exception|
    redirect_to root_url, alert: exception.message
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :name
  end
end

This is application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

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

def index?
  false
end

def show?
  scope.where(:id => record.id).exists?
end

def create?
  user.present?
end

def new?
  create?
end

def update?
  user.present? && (record.user == user || user.admin?)
end

def edit?
  update?
end

def destroy?
  update?
end

def scope
  record.class
end

  class Scope
    attr_reader :user, :scope

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

    def resolve
      scope
    end

  end

end

This is post_policy.rb

class PostPolicy < ApplicationPolicy
  def new
    @post = Post.new
      authorize @post
  end
end

This is posts_controller.rb

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    #ApplicationController::Find
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
  end

    def create
      @post = current_user.posts.build(params.require(:post).permit(:title, :body))
      if @post.save
        flash[:notice] = "Post was saved."
        redirect_to @post
      else
        flash[:error] = "There was an error saving the post. Please try again."
        render :new
      end
    end


  def edit
    @post = Post.find(params[:id])
  end

    def update 
      @post = Post.find(params[:id])
      if @post.update_attributes(params.require(:post).permit(:title, :body))
        flash[:notice] = "Post was updated."
        redirect_to @post
      else
        flash[:error] = "There was an error saving the post. Please try again."
      end
    end
end
user3640511
  • 167
  • 2
  • 12

1 Answers1

0

The issue was that I defined another new method in the post_policy.rb file, overwriting the new method in application_policy.rb. I also didn't include authorize @post in the new method in the posts_controller.rb file.

user3640511
  • 167
  • 2
  • 12