0

我正在尝试向我的 Rails 应用程序添加授权,并希望将非用户重定向到root_url他们尝试访问帖子/新内容时,使用rescue_from. 但是,没有重定向到根目录或显示错误消息,我不知道为什么。

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

1 回答 1

0

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

于 2015-02-26T05:28:30.023 回答