0

我正在使用CanCanCan gem (v.12.0) 进行基本授权。我的User模型不使用角色的概念。我要做的就是确保用户在他们可以对我的主模型做任何事情之前登录,Topic.

我相信我已经Ability正确地写了我的课。不出所料, MyTopicsController有一种index方法可以显示用户的所有主题。

问题是,当没有登录用户时,第一个if成功index.html.erb- 这对我来说没有意义。我错过了一些明显的东西吗?

# ability.rb    
class Ability
  include CanCan::Ability

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

    # as long as a user is logged in and owns the topic it can do anything it likes with it
    can [:manage], Topic do |topic|
      !user.new_record? && topic.try(:user) == user
    end
end

--

# topics_controller.rb
class TopicsController < ApplicationController
  load_and_authorize_resource # CanCanCan gem

  def index
  end
  ...
end

--

# index.html.erb
<% if can? :read, Topic %>
  <% @topics.each do |topic| %>
    <%# Display all the topics %>
<% else %>
  <%# Handle the case where the user can't read Topics %>
<% end %>
4

1 回答 1

1

您需要为特定实例授权用户:

<%= if can? :read, topic %>

当您尝试为整个类授权用户时,如上所述,CanCanCan 会忽略能力中定义的任何条件,因为它无法确定user整个Topic模型的关系;它只能对单个topic实例执行此操作。不幸的是,AFAIK 无法授权关系,因此您必须为关系中的每个实例授权。

或者,在版本 1.4中,load_and_authorize_resource控制器中的初始化应该@topics基于current_user仅当能力被定义为没有块时。但是,“手动”执行此操作几乎是微不足道的:

@topics = current_user.topics
于 2015-08-12T01:32:10.230 回答