0

I want to use Protector to control the fields that unauthorized users can see on my models but I'm having trouble using it to hide associations.

I have a project model and a post model. They partially look like this.

class Project < ActiveRecord::Base
  has_many :posts
  protect do
    can :read, %w(title)
    cannot :read, %w(posts)
  end

end

class Post < ActiveRecord::Base
  belongs_to :project
  protect do
    cannot :read
  end
end

Now let's say I create some records that look like this

Project.create(title: 'project one')
User.create(email: 'example@user.com')
Post.create(project_id: Project.first.id, title: 'post one')
Post.create(project_id: Project.first.id, title: 'post two')

When I ask for Project.first.restrict!(User.first).posts I get a non-empty ActiveRecord relation. I can't access the titles of the objects in the relation, but I can see their IDs and how many posts there are. I'd rather be able to restrict access to the Project object so that no posts are returned at all. Is this possible with Protector or should I look for another solution?

4

1 回答 1

0

这里的问题是你滥用它:)。你不应该试图让你的关联不可读,因为它在 ActiveRecord 方面并不是真正的价值。这是一个关系。

所以要让事情发挥作用——你必须使用作用域。适当地添加scope {}到您的Post模型中。然后,当您调用它时.postsProject它会给您一个Post受同一用户限制的 s 关系。并且模型的描述scope {}Post将适用。

再说一遍:不要试图描述关联模型——使用它们自己的保护块来定义它们的独立行为。这就是 Protector 的封装方式。

于 2013-11-01T09:27:07.443 回答