1

我現在的索引操作是這樣的:權威人士範圍軌關係

def index 
    @proposals = current_user.proposals 
    end 

但我想這樣做是這樣的:

def index 
    @proposals = policy_scope(Proposal) 
    end 

我有UserProposal之間的has_and_belongs_to關係。

我開始在我的應用程序中使用Pundit gem,但我不知道如何定義範圍以便具有上面爲普通用戶顯示的行爲。

我想要做這樣的事情:

class Scope < Scope 
    def resolve 
     if user.admin? 
     scope.all 
     else 
     user.proposals # HOW DO I DO THIS WITH THE SCOPE? 
     end 
    end 
    end 

我如何使用範圍變量user.proposals? 我知道,如果我有一個has_manybelongs_to關係,我可以這樣做:

 else 
     scope.where(user_id: user.id) # RIGHT? 
     end 

但在HABTM的情況下,我不知道該怎麼做。

任何幫助?

回答

5

您可以使用joins來獲取與用戶相關的提案。就像這樣:

def resolve 
    if user.admin? 
    scope.all 
    else 
    scope.joins(:users).where(proposals_users: { user_id: user.id }) 
    end 
end 
+0

非常感謝@AlexanerTipugin,它的工作原理! – Mario

+0

這正是我在找的東西。 – Mario