我正在使用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 %>