Rails CanCan - 定义嵌套模型的权限
我有两个模型:
Thread (id, title)
ThreadParticipation (id, thread_id, user_id)
我想定义类似的内容:
can :create, ThreadParticipation if the user is a ThreadParticipation
示例:
for
thread: (1, 'hello world')
thread_participation: (313, 1, 13) -- where 13 is the user_id
我尝试过:
can :create, ThreadParticipation, :thread_participations => { :user_id => current_user.id }
但是错误。有什么想法吗?
I have two models:
Thread (id, title)
ThreadParticipation (id, thread_id, user_id)
I want to define something like:
can :create, ThreadParticipation if the user is a ThreadParticipation
example:
for
thread: (1, 'hello world')
thread_participation: (313, 1, 13) -- where 13 is the user_id
I tried:
can :create, ThreadParticipation, :thread_participations => { :user_id => current_user.id }
But that errors. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,
Thread
只是一个糟糕的模型名称,因为它会与 Ruby 中定义的Thread
类发生冲突。我最近才实施了这个。在我的示例中,我有论坛和主题。一个人不应该能够在他们没有读取权限的论坛中创建新主题。我在论坛对象上定义了一个名为
create_topic
的自定义权限:其中
can_create_forem_topics?
只是在User
模型上定义,如下所示:然后我只需在我的
TopicsController
中的new
和create
操作中使用此自定义:create_topic
功能,其中@ forum
由before_filter
定义:如果我需要在视图中使用它:
通过在父对象上定义自定义权限,
Thread
in general is just a bad model name, because it will clash with theThread
class defined in Ruby. I implemented this just recently. In my example, I have forums and topics. A person shouldn't be able to create a new topic in a forum they don't have read access to.I defined a custom permission on the Forum object called
create_topic
for this:Where
can_create_forem_topics?
is just defined on theUser
model like this:Then I just use this custom
:create_topic
ability in thenew
andcreate
actions in myTopicsController
, where@forum
is defined by abefore_filter
:And if I need to use it in views:
by defining a custom permission on the parent object,
我目前正在尝试实现类似的目标,但我对此没有全面的了解。试试这个:
这应该也可以在没有阻塞的情况下工作。
编辑:删除上面的部分,这在 CanCan 中还不起作用。我实现了自己的解决方案,但它需要您手动授权控制器操作,这不是那么美化,但在我看来更安全。
我在我的项目中是这样实现的:
https://gist.github.com/822208
I'm currently trying to achieve something similiar, but I don't have the whole sight into this. Try this:
This should also work without a block.
EDIT: drop the part above, that doesn't work yet in CanCan. I implemented my own solution, but it requires you to authorize controller actions manually, which is not as beautify, but more secure in my opinion.
I implemented it this way for my project:
https://gist.github.com/822208
通常你
不会 使用
ability.rb 中的current_user
。这是你的错误吗?而且你的能力指定不正确。您要
注意 :user_id 是 ThreadParticipation 模型的属性
Normally you would user
not
current_user
within ability.rb. Is this your error? As well your ability is specified incorrectly. You want
Note that :user_id is a property of ThreadParticipation model