如何处理 cancan 中由父对象定义的 :create 权限?

发布于 2025-01-07 13:48:15 字数 397 浏览 0 评论 0原文

假设您正在为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不必了 2025-01-14 13:48:15

根据当前对象的父级定义能力:

can :create, Post, :blog => { :user => user }

这将确保当前用户只能为其拥有的博客创建新的帖子记录。

  • 使用 Post.blog_id 查找父 Blog 记录
  • Blog.user_id 字段与 current_user.id 字段进行比较

同时确保您在加载和授权 Post 资源时使用 :through 声明,以便 CanCan 知道父记录是谁。

PostsController:

load_and_authorize_resource :through => :blog

有关更多详细信息,请参阅 GitHub 上的 CanCan wiki

Define an ability based on the parent of the current object:

can :create, Post, :blog => { :user => user }

This will make sure the current user can only create a new Post record for a blog that they are an owner of.

  • uses Post.blog_id to find parent Blog record
  • compares Blog.user_id field to current_user.id field

Also make sure that you are using a :through declaration when loading and authorizing your Post resource, so CanCan knows who the parent record is.

PostsController:

load_and_authorize_resource :through => :blog

See the CanCan wiki on GitHub for more detail.

坏尐絯 2025-01-14 13:48:15

您可以使用

用户可以吗? :创建帖子,@current_blog

user.can?:更新,@current_blog

而不是

用户可以吗? :创建,发布,@current_blog

。当然,您可能需要从 load_and_authorize_resource 中取出 newcreate 操作。并自行测试“授权”

定义新
未经授权!如果不能? :创建帖子,@current_blog
结束

You can use

user.can? :create_posts, @current_blog

or

user.can?:update, @current_blog

instead of

user.can? :create, Post, @current_blog

. Of course, you probably need to take out new and create action from load_and_authorize_resource. And test "authorization" by yourself

def new
unauthorized! if cannot? :create_posts, @current_blog
end

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文