如何处理 cancan 中由父对象定义的 :create 权限?
假设您正在为 Blogger 编写软件。
每个用户只有成为博客的所有者才能创建博客文章。 CanCan 通常将这种情况下的能力检查定义为:
user.can? :create, Post
但是,用户只有在是当前博客的所有者时才能创建帖子,并且无法仅使用其类名来引用当前博客。我真正需要做的是:
user.can? :create, Post, @current_blog
这样在康康定义中我可以说
can :create, Post do |post, blog|
user == blog.owner
end
这可能吗?或者我对如何处理这个问题感到困惑?
Let's say you're writing the software for Blogger.
Each user can create a blog post only if they are the owner of the blog. CanCan would normally define an ability check in this circumstance as:
user.can? :create, Post
However the user can only create the post if they are the owner of the current blog and there's no way to reference the current blog using only its classname. What I really need to be able to do is:
user.can? :create, Post, @current_blog
such that in the cancan definitions I can say
can :create, Post do |post, blog|
user == blog.owner
end
Is that possible or am I confused in how I'm approaching this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据当前对象的父级定义能力:
这将确保当前用户只能为其拥有的博客创建新的帖子记录。
Post.blog_id
查找父Blog
记录Blog.user_id
字段与current_user.id
字段进行比较同时确保您在加载和授权 Post 资源时使用
:through
声明,以便 CanCan 知道父记录是谁。有关更多详细信息,请参阅 GitHub 上的 CanCan wiki。
Define an ability based on the parent of the current object:
This will make sure the current user can only create a new Post record for a blog that they are an owner of.
Post.blog_id
to find parentBlog
recordBlog.user_id
field tocurrent_user.id
fieldAlso make sure that you are using a
:through
declaration when loading and authorizing your Post resource, so CanCan knows who the parent record is.See the CanCan wiki on GitHub for more detail.
您可以使用
或
而不是
。当然,您可能需要从
load_and_authorize_resource
中取出new
和create
操作。并自行测试“授权”You can use
or
instead of
. Of course, you probably need to take out
new
andcreate
action fromload_and_authorize_resource
. And test "authorization" by yourself