【发布时间】:2016-12-08 18:44:22
【问题描述】:
在使用 Pundit 时,我正在努力授权嵌套资源的索引操作。 Pundit 如此狡猾且可能很容易,我讨厌不得不将其抛在一边,因为我无法弄清楚这一点。我想一旦我理解了这部分,其他一切都会顺理成章。我已经阅读了很多人的帖子,他们提出的问题与我所问的问题非常相似,似乎最接近我所问问题的帖子永远不会得到解决。所以,我还在寻找答案。
class User < ApplicationRecord
enum role: [:user, :admin]
after_initialization :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :user
has_many :galleries, dependent: :destroy
end
class Gallery < ApplicationRecord
belongs_to :user
validates :user_id, presence: true
validates :title,, presence: true
end
我已经通过 UserPolicy 设置了我想要的用户。它没有从 ApplicationPolicy 继承,因为我正在查看的教程说我不需要它。
我的路线如下所示:
devise_for :users, path: 'accounts
resources :users, shallow: true do
resources :galleries
end
基本上我不希望一个用户看到另一个用户的东西,即索引、显示......操作。我相信这被称为封闭系统。我查看用户图库(我的嵌套资源)索引的路径如下所示:
localhost:/users/20/galleries
我不希望用户 19 看到用户 20 在其图库索引中的内容。我该怎么做?
这就是我的 GalleryController 的样子:
before_action :authenticate_user! #I'm using devise
def index
@galleries = current_user.galleries.all
#authorize ????? <<part of what I don't understand
end
private
def gallery_params
params.require(:gallery).permit(:title)
end
我真的不知道我应该在 GalleryPolicy 中为索引做什么。我已经制定了显示操作,因为它只是根据用户 ID 的实例检查画廊的实例。这是 GalleryPolicy
attr_reader :user, :model
def initialize(user, model)
@user = user
@gallery = gallery
end
def show?
@gallery.user_id == user.id
end
def index?
# I can't figure it out
end
def new?
#actually this is confusing too
end
【问题讨论】:
标签: ruby-on-rails nested authorization ruby-on-rails-5 pundit