【问题标题】:Checking Ability in cancan在康康检查能力
【发布时间】:2012-12-02 17:46:19
【问题描述】:

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

我遇到了两个问题。

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

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

这是我的用户模型:

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

在我的 Instructors 控制器中,我已将“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 %>

非常感谢所有帮助。

谢谢

斯科特

【问题讨论】:

    标签: ruby-on-rails-3.2 authorization cancan


    【解决方案1】:

    不是这个

    <% if can? :manage, Instructor %>
    

    试试这个

    <% if user.has_role? :admin %>
    

    (假设在您的应用中,管理员管理/拥有比教师更多的权限。)

    【讨论】:

      【解决方案2】:

      我变了:

      if user.admin?
      

      if user.id
      

      而且效果很好

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-02
        • 2021-09-13
        相关资源
        最近更新 更多