Predit

2017-05-18 5 views
0

에 따라 권한을 부여 할 때 레코드 대신 부울 값 가져 오기 the Pundit readmeauthorize에 따르면 레코드를 반환해야하지만 아직 호출 할 때는 true이됩니다.Predit

권한 부여가 전달 된 객체를 반환, 그래서 당신은 이처럼 체인 수 있습니다

컨트롤러 :

def show 
    @user = authorize User.find(params[:id]) 
end 

Gemfile :

gem 'rails', '~> 5.1.1' 
gem 'devise', '~> 4.3' 
gem 'pundit', '~> 1.1' 

내 컨트롤러 :

,
class PostsController < ApplicationController 
    skip_before_action :authenticate_user!, only: [:show, :index] 
    before_action :set_post, only: [:show, :edit, :update, :destroy] 

    def show 
    # just for debugging purposes 
    raise "Post is a #{@post.class.name}!" unless @post.is_a? Post 
    end 

    def set_post 
    # this should return an instance of post 
    @post = authorize Post.find(params[:id]) 
    end 
end 

정책 :

class PostPolicy < ApplicationPolicy 

    class Scope < Scope 
    def resolve 
     scope.all 
    end 
    end 

    def show? 
    true 
    end 

    # ... 
end 

사양 :

require 'rails_helper' 
RSpec.describe "Posts", type: :request do 
    subject { response } 

    describe "GET /posts/:id" do 
    let!(:post) { create(:post) } 
    before { get post_path(post) } 
    it { should be_successful } 
    end 
end 

오류 메시지 : 동안

4) Posts GET /posts/:id 
    Failure/Error: raise "Post is a #{@post.class.name}!" unless @post.is_a? Post 

    RuntimeError: 
     Post is a TrueClass! 

의하면 문제를 해결할 아주 간단합니다 :

def set_post 
    @post = Post.find(params[:id]).tap do |p| 
    @post = Post.find(params[:id]).tap { |r| authorize r } 
    end 
end 

나는 왜 readme에 명시된대로 작동하지 않는지에 대해 궁금합니다. 이 버그입니까 아니면 그냥 뭔가 빠졌습니까?

답변

0

레코드를 반환하는 것은 분명히 1.1 릴리스에 반영되지 않은 마스터의 변경입니다.

# Retrieves the policy for the given record, initializing it with the 
# record and user and finally throwing an error if the user is not 
# authorized to perform the given action. 
# 
# @param user [Object] the user that initiated the action 
# @param record [Object] the object we're checking permissions of 
# @param record [Symbol] the query method to check on the policy (e.g. `:show?`) 
# @raise [NotAuthorizedError] if the given query method returned false 
# @return [true] Always returns true 
def authorize(user, record, query) 
    policy = policy!(user, record) 

    unless policy.public_send(query) 
    raise NotAuthorizedError, query: query, record: record, policy: policy 
    end 

    true 
end 

해결 방법은 다음과 같습니다

def authorize(record, query = nil) 
    super 
    record 
end