ruby on rails -不能使用Pundit授权嵌套资源



我的问题是。我有多个用户与多个订阅每个,我想授权订阅索引方法与Pundit。我的 routes.rb :

资源:用户做资源:订阅之前结束

假设我是id 1的用户。我需要的是获得订阅列表,当我打开/users/1/subscriptions和Pundit访问错误,当我打开/user/2/subscriptions

这是我的subscriptions_controller.rb

<>以前SubscriptionController & # 60;程序控制器def指数@user = User.find(params[:user_id])@subscriptions = @user.subscriptions授权@subscriptions结束之前结束

我可以做authorize @user, :subscriptions_index,但是为订阅认证编写用户策略感觉不对。我该如何处理这个问题?

这应该为您工作(可能不是最有效的):

class SubscriptionController < ApplicationController
  def index
    @user = User.find(params[:user_id])
    # this should either return the same or an empty association
    @subscriptions = @user.subscriptions
    authorize @subscriptions
  end
end
class SubscriptionPolicy < ApplicationPolicy
  def index?
    # asking if all subscriptions have the current_user id as the user_id
    record.all? {|sub| sub.user_id == user.id }         
  end
end

最新更新