2016-10-04 33 views
4

我已經從我2年的努力中嘗試瞭解如何在我的rails應用程序中使用pundit進行了長時間的休息。我回來了,並試圖學習如何使用專家。Rails 5 - 如何使用Pundit

我做了一個全新的rails 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類(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的操作....

相關問題