CanCanCan gem:处理没有登录用户的情况

时间:2015-08-11 21:16:40

标签: ruby-on-rails authorization cancan cancancan

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

我相信我已正确地写了Ability课程。我的TopicsControllerindex方法,毫不奇怪,它显示了用户的所有主题。

问题是,当没有登录用户时,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 %>

1 个答案:

答案 0 :(得分:1)

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

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

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

或者,控制器中的in version 1.4load_and_authorize_resource只有在{<>>没有块的情况下才能根据@topics初始化current_user。然而,它的“手动”几乎是微不足道的:

@topics = current_user.topics