当非用户访问帖子/新帖时,Pundit rescue_from不会重定向或显示警报消息

时间:2015-02-26 00:22:35

标签: ruby-on-rails authorization pundit

我尝试向rails应用添加授权,并希望在用户root_url尝试访问帖子/新帖时将非用户重定向到rescue_from。但是,没有重定向到root或显示错误消息,我不确定原因。

这是我的 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

这是 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

这是 post_policy.rb

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

这是 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

1 个答案:

答案 0 :(得分:0)

问题是我在post_policy.rb文件中定义了另一个new方法,覆盖了application_policy.rb中的new方法。我还没有在posts_controller.rb文件的authorize @post方法中包含new