如何将 CanCanCan 与枚举字段一起使用?

How to use CanCanCan with enum field?

我得到了带有枚举字段 enum status: [:pending, :done]Article 模型。

这是我的能力文件

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.member?
      can :read, Article.done
    end
  end
end

鉴于我正在尝试为成员呈现 Article.done 集合,但没有呈现。

<% if can? :read, Article.done %> 
  <%= render partial: 'article', collection: Article.done, as: :article %>
<% end %>

因此我有一个问题:有没有可能在 CanCanCan 中使用枚举的方法?

我可能错了,但我认为 enum 只会创建 instance 方法:

@article = Article.find params[:id]
@article.done?

I was wrong...

Scopes based on the allowed values of the enum field will be provided as well. With the above example:

Conversation.active
Conversation.archived

--

如果不行我就删了;我会根据 hash of conditions,而不是 class 本身进行评估:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.member?
      can :read, Article, status: Article.statuses[:done]
    end
  end
end

更新

需要考虑的几个重要事项。

首先,当使用hash条件时:

Important: If a block or hash of conditions exist they will be ignored when checking on a class, and it will return true.

这意味着您不能在传递 class 的同时调用 "ability" 的特定条件,它必须在对象的实例上调用。

其次,似乎CanCanCan has some issues evaluating enum values,这就需要下面的代码:

#app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.member?
      can :read, Article do |article|
        article.done?
      end
    end
  end
end

然后您需要将 article 实例传递给 can? 方法:

#app/views/articles/index.html.erb
<table>
    <%= render @articles %>
</table>

#app/views/articles/_article.html.erb
<% if can? :read, article %>
    <tr>
      <td>Title:</td>
      <td><%= article.title %></td>
      <td><%= article.status %></td>
    </tr>
<% end %>