2016-10-04 15 views
4

私は2年間の努力から、私のレールアプリで専門家の使い方を学ぶことに長い間休憩してきました。私は学識者を使う方法を学びたいと考えています。Rails 5 - Punditの使い方

私は全く新しいレール5アプリとインストールされた専門家を作りました。

私はユーザーリソース、アプリケーションポリシー、およびユーザーポリシーを持っています。それぞれが持っている:

ユーザーコントローラ:

def index 
    # @users = User.all 
    @users = policy_scope(User) 
    end 

アプリケーションポリシー

class ApplicationPolicy 
    attr_reader :user, :record 

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

    def index? 
    true 
    end 

    def show? 
    scope.where(:id => record.id).exists? 
    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 

ユーザーポリシー

class UserPolicy < ApplicationPolicy 
    class Scope < Scope 
    def resolve 
     scope.where(user: user) 
    end 
    end 


end 

はその後、私のユーザーインデックスでは、私はの指示に従うことをしようとしています上級者の宝石のドキュメント、行うことによって:

<% policy_scope(@users).each do |user| %> 

は、私はこのエラーを取得する:

PG::UndefinedColumn: ERROR: column users.user does not exist 
LINE 1: SELECT "users".* FROM "users" WHERE "users"."user" = '566119... 
              ^
: SELECT "users".* FROM "users" WHERE "users"."user" = '566119d2-54d8-4ab2-b7c5-f17c80b517f3' AND "users"."user" = '566119d2-54d8-4ab2-b7c5-f17c80b517f3' 

誰も私が間違ってスタートを切っ取得していますどのように見ることができますか?私はまだ私が望む方法で範囲を定義しようとしなかったが、現時点では機能していない。

+1

多分あなたは 'scope.where(id:user.try(:id))'を意味しましたか? – slowjack2k

答えて

1
class UserPolicy < ApplicationPolicy 
    class Scope < Scope 
    def resolve 
     scope.where(user: user) 
    end 
    end 
end 

scope.whereは、ユーザーポリシー内にあるため、ユーザークラス(user.where)を意味します。

ユーザー値は、アプリケーションスコープによって継承された現在のユーザーです。

投稿したスコープの例私はあなたが現在のユーザーレコードのみを表示したいと思っています。あなたはあなたがビューに別のものを定義する必要はありませんコントローラ

def index 
    # @users = User.all 
    @users = policy_scope(User) 
end 

にスコープを定義しているので、

また
scope.where(id: user.try(:id)) 

:次に、あなたは上記のコメントとして次の操作を行うことができます。

<% policy_scope(@users).each do |user| %> 

これはどちらか一方です。ビューでは、簡単にusers.each doを行うことができます。

関連する問題