如何使用Protector基于关联限制模型?

时间:2013-07-09 07:33:41

标签: ruby activerecord protector

取自:https://github.com/inossidabile/protector/issues/10

我希望能够根据加入表设置权限。

所以...

Post.restrict!(current_user).joins(:category)

在这种情况下,当前用户无法直接访问类别,但可以通过Post获取类别。我怎么做到这一点?它正在应用默认的类别范围,我没有看到根据连接表使其成为条件的方法。

1 个答案:

答案 0 :(得分:0)

请仔细阅读:https://github.com/inossidabile/protector#self-aware-conditions。如您所见,您可以接受限制块的第二个参数。在里面,您可以获得其任何属性或任何嵌套关联。所以在你的情况下它可能是这样的:

protect do |user, post|
  if post.try(:category) && post.category.anything == 'foobar'
    # Whatever you want to allow or disallow here
  end
end