在cancan中检查能力



我是一个相对的新手,我正试图让cancan在一个简单的项目中工作。我关注了Railscast并阅读了文档,但我遗漏了一些东西。

我有两个问题。

  1. 我为普通用户正确隐藏了编辑/创建链接。但是,它们也对管理员用户隐藏
  2. 如果我注释掉了隐藏上面链接的代码,当管理员用户点击它们时,他们会收到一条拒绝访问的消息,该消息应该为非管理员用户显示

所以我认为我的问题是应用程序没有正确检查能力。我已经检查了数据库,并且角色列正确地填充了该用户的"admin"。

这是我的用户模型:

class User < ActiveRecord::Base
has_secure_password
#this is for authentication
attr_accessible :email, :password, :password_confirmation, :role
validates_uniqueness_of :email
#end of authentication
end

在我的讲师控制器中,我在顶部添加了"load_and_authorize_resource"。

我的Ability.rb文件看起来像这个

class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
else
can :read, :all
end
end
end

我的视图中我隐藏了基于角色的控件我有这样的代码:

<% if can? :manage, Instructor %>
<td><%= link_to 'Edit', edit_instructor_path(instructor) %></td>
<td><%= link_to 'Destroy', instructor, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>

我们非常感谢所有的帮助。

感谢

Scott

而不是这个

<% if can? :manage, Instructor %>

试试这个

<% if user.has_role? :admin %>

(假设在你的应用程序中,管理员管理/拥有比讲师更多的权限。)

我更改了:

if user.admin?

if user.id

它的工作得很好

最新更新