【问题标题】:Setting roles for a users in rails with cancan使用 cancan 为 Rails 中的用户设置角色
【发布时间】:2012-07-25 16:00:32
【问题描述】:

我正在开发一个 Rails 应用程序,它需要两种不同类型的角色。一个是员工,另一个是管理员。

Cancan 文档说它假定应用程序中有一个 user 或 current_user 方法。

那么如何使用 cancan 在我的应用中为员工和经理设置角色?

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    这样做

    在应用程序助手中写这个

    def is_employee?(user)
      emp_role = Role.find(:first, :conditions => ["name = ?", "Employee"])
      return user.roles.include?(emp_role)
    end
    
    def is_admin?(user)
      admin_role = Role.find(:first, :conditions => ["name = ?", "Admin"])
      return user.roles.include?(admin_role)
    end
    

    而且看起来像这样

         class Ability
           include CanCan::Ability
           include ApplicationHelper
    
        def initialize(user)
          # Define abilities for the passed in user here. For example:
           #
          user ||= Employee.new # guest user (not logged in)
          if is_admin?(user)
           can :manage, :all
           # cannot :manage, IpAddress
         elsif is_employee?(user)
    
          #your code
         end
    

    定义角色见

       http://stackoverflow.com/questions/10222400/rails-adding-an-admin-role-using-devise-who-can-see-all-the-users/10222813#10222813
    

    确实有效...

    【讨论】:

    • 我没有用户类。我有 Employee 类,我想从那里设置角色。
    • 是的,我已经安装了 devise 并将其设置为 Employee 模型
    • 在 cancan 中是否可以使用其他名称覆盖用户?
    • 只有在将 User.new 替换为 Employee.new 的情况下才能改变
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2011-06-25
    • 2012-05-20
    • 2013-05-07
    • 2013-02-06
    • 1970-01-01
    相关资源
    最近更新 更多