1

我有两个模型:

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 }

但是那个错误。有任何想法吗?

4

3 回答 3

1

Thread通常只是一个糟糕的模型名称,因为它会与ThreadRuby 中定义的类发生冲突。我最近才实现了这一点。在我的示例中,我有论坛和主题。一个人不应该能够在他们没有阅读权限的论坛中创建新主题。

我在 Forum 对象上定义了一个自定义权限create_topic,为此调用:

can :create_topic, Forem::Forum do |forum|
  can?(:read, forum) && user.can_create_forem_topics?(forum)
end

Wherecan_create_forem_topics?只是在User模型上定义,如下所示:

def can_create_forem_topics?(forum)
  # code goes here
end

然后我只是在 my 的and操作中使用此自定义:create_topic功能,其中由 a 定义:newcreateTopicsController@forumbefore_filter

authorize! :create_topic, @forum

如果我需要在视图中使用它:

can? :create_topic, @forum

通过在父对象上定义自定义权限,

于 2011-11-27T01:38:08.383 回答
0

我目前正在尝试实现类似的目标,但我并没有完全了解这一点。尝试这个:

can :create, ThreadParticipation => Thread, do |participation, thread|
  # your definition here
end

这也应该在没有块的情况下工作。

编辑:删除上面的部分,这在 CanCan 中还不起作用。我实现了自己的解决方案,但它需要您手动授权控制器操作,这不是美化的,但在我看来更安全。

我以这种方式为我的项目实现了它: https ://gist.github.com/822208

于 2011-02-11T08:31:44.503 回答
0

Normally you would user

user

not current_user

within ability.rb. Is this your error? As well your ability is specified incorrectly. You want

can :create, ThreadParticipation, :user_id => user.id

Note that :user_id is a property of ThreadParticipation model

于 2012-03-07T07:23:42.077 回答