[英]Rails - Pundit with scopes
我試圖弄清楚如何在我的Rails 4應用程序中寫入專家權限。
我有一個帶有商品政策的商品模型。 文章政策具有:
class ArticlePolicy < ApplicationPolicy
attr_reader :user, :scope
def initialize(user, record, scope)
@scope = scope
super(user, record)
end
class Scope < Scope
def resolve
if user == article.user
scope.where(user_id: user_id)
elsif approval_required?
scope.where(article.state_machine.in_state?(:review)).(user.has_role?(:org_approver))
else
article.state_machine.in_state?(:publish)
end
end
end
# TO DO - check if this is correct - I'm not sure.
# I now think I don't need the index actions because I have changed the action in the articles controller to look for policy scope.
# def index?
# article.state_machine.in_state?(:publish)
# end
def article
record
end
Articles控制器具有:
def index
@articles = policy_scope(Article)
# query = params[:query].presence || "*"
# @articles = Article.search(query)
end
我正在關注與范圍有關的權威文件,並試圖弄清楚為什么政策文件中顯示的索引操作對我不起作用。 我已經嘗試了以下方法(如文檔所示):
<% policy_scope(@user.articles).sort_by(&:created_at).in_groups_of(2) do |group| %>
但是我得到這個錯誤:
undefined local variable or method `article' for #<ArticlePolicy::Scope:0x007fff08ae9f48>
誰能看到我哪里出問題了?
我不確定@ user.articles是否正確。 在我的構造中,文章屬於用戶,但是在索引操作中,我想向每個用戶展示我的范圍允許他們查看的文章。
您可以在控制器中的操作中嘗試此操作。
@articles = policy_scope(Article).all
它將獲取所有文章。 如果要基於搜索參數獲取文章,則可以嘗試此操作。
@q = policy_scope(Article).search(params[:query])
@articles = @q.result
我認為您可能需要在Scope類中將article顯式設置為訪問器,因為錯誤表明它無法識別“ article”。 嘗試類似
attr_accessor :article
將其設置為initialize方法,您可能可以取消article方法。
def initialize(record)
@article = record
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.