0

这是另一个问题的后续,因为我注意到我的问题比那里描述的要普遍得多。

在使用 JSONAPI::Resources 和 CanCanCan 的 Rails 应用程序中,我有一个Caption模型 ( belongs_to :video) 和一个Video模型 ( has_many :captions)。为了定义能力,我使用了一个ability.rb我归结为测试目的的文件:

class Ability
  include CanCan::Ability

  def initialize(person)
    guest_actions
    user_actions(person)
  end

  def guest_actions
    # Guests can only access those captions which belong to a published video
    can :read, Caption, video: { visible: true }
  end

  def author_actions(person)
    # Registered users are only allowed to add captions to their own videos
    can %i[create destroy], Caption, video: { creator: { id: person.id } }
  end
end

但是,这是行不通的。这些具体的能力定义似乎并没有被忽视,而是被错误地解读了:

  • 客人实际上可以访问所有字幕。如果我删除上面的行guest_actions,客人将无法访问任何标题并收到401 Unauthorized
  • 除非我删除author_actions.

两者CaptionControllerVideoController扩展ApplicationController,其中包含load_and_authorize_resource only: %i[index show create update destroy].

关于这种特定关系,我注意到一件事:当我打开 Rails 控制台或运行 RSpec 时,会出现意外警告:

DEPRECATION WARNING: In CaptionResource you exposed a 'has_one' relationship using the 'belongs_to' class method. We think 'has_one' is more appropriate.

我对此感到惊讶,因为我的Caption模型包含一个video_id字段。我暂时将关系更改为has_one(仅在资源中以及模型和资源中),但它在我的测试中没有任何区别。

我的代码有什么问题?我有一些以类似方式定义的能力,但我无法弄清楚Caption.

4

0 回答 0