Ruby - Rails 4 - Pundit - 路由#index_fr的策略和授权错误?

时间:2016-10-26 10:15:53

标签: ruby-on-rails routes authorization policy pundit

对不起,我没有看到另一个地方询问关于Pundit的问题......谢谢你的帮助。

我正在开发一个Ruby on rails API,我想创建一个url(... / api / v1 / attractions / fr)列出一些关于我的模型的信息。但我从Pundit收到了这条错误消息:

  

Pundit :: AuthorizationNotPerformedError at / api / v1 / attractions / fr   API :: V1 :: AttractionsController

和lib / pundit.rb文件中的verify_authorized的此错误

def verify_authorized
    raise AuthorizationNotPerformedError, self.class unless pundit_policy_authorized?
end

这是我的配置:

# app/config/routes.rb

namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :lines, only: [ :index, :show ] do
        collection do
          get '/fr', to: 'attractions#index_fr'
        end
      end
   end
end

# app/controllers/api/v1/attractions_controller.rb

class Api::V1::AttractionsController < Api::V1::BaseController
skip_before_action :authenticate_user!

  def index
    @attractions = policy_scope(Attraction)
    @attractions = Attraction.all
  end

  def index_fr
    @attractions = policy_scope(Attraction)
    @attractions = Attraction.all
  end
end

# app/policies/application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

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

  def index?
    false
  end

  def index_fr?
    false
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  class Scope
    attr_reader :user, :scope

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

    def resolve
      scope
    end
  end
end
end

1 个答案:

答案 0 :(得分:0)

尝试将before_filter :skip_authorization添加到您的api控制器。

但是,如果您将verify_authorized方法添加为after_action,则只应调用它。