我正在使用CanCanCan gem(v.12.0)进行基本授权。我的User
模型不使用角色的概念。我所要做的就是确保用户在使用我的主模型Topic
做任何事情之前都已登录。
我相信我已正确地写了Ability
课程。我的TopicsController
有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 %>
答案 0 :(得分:1)
您需要为用户授权特定实例:
<%= if can? :read, topic %>
当您尝试为整个班级授权用户时,CanCanCan会忽略能力中定义的任何条件,因为它无法确定整个user
模型的Topic
关系;它只能对单个topic
实例执行此操作。不幸的是,AFAIK无法授权关系,因此您必须为关系中的每个实例进行授权。
或者,控制器中的in version 1.4,load_and_authorize_resource
只有在{<>>没有块的情况下才能根据@topics
初始化current_user
。然而,它的“手动”几乎是微不足道的:
@topics = current_user.topics