如何检查当前用户是否为rails中的admin?

时间:2017-06-13 21:15:07

标签: ruby-on-rails

如果他们向我(管理员)支付了现金,我必须更改客户表格。假设现金,而不是现金。所以为了改变形式,我使用了这样的东西:

if current_user.user_type == :client
    show normal form 
elsif current_user.user_type == :admin
    show normal form + more functionality
end

那么实现“user_type”功能的最佳方法是什么?我正在考虑将该函数添加到User类,如下所示。退货:卖家和退货:客户工作正常。我测试过了。我可以查看当前用户的电子邮件和密码(current_user是我,使用已经输入的密码和电子邮件)?这似乎不起作用。什么是最好的方法呢?

class User < ActiveRecord::Base
  has_one :client
  has_one :seller

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  acts_as_messageable

     def user_type
         return :client if self.client(&:info_complete?)
         return :seller if self.seller(&:info_complete?)
         return :admin if (self.email == 'admin@gmail.com' && self.password == 'admintestpass')
     end  
end

1 个答案:

答案 0 :(得分:1)

好的,首先你需要创建一个迁移来添加一个列(我将它命名为role,不要使用type,因为它会在以后导致问题)到用户表。我假设您知道如何编写迁移,如果没有在评论中请求示例。该列必须是int类型。 null: false, defaul: 0是一个好主意,可以避免某些用户没有角色。然后是模型:

这是rails枚举节省的一天。对于我的示例,假设该列名为role

    model User < ApplicationRecord #boilerplate stuff
      enum role: [ :client, :seller, :admin ] # These are the different possible roles

      def assign_role
        if # logic to decide role here
          self.update_attribute(:role, :admin) # This makes the user admin
        else
          self.update_attribute(:role, :client) # This makes the user client
        end
      end
    end

注意:enums不需要assign role方法,我只是添加了它,以便您可以看到如何分配角色并将其保存给用户。

然后在您的控制器中(或根据需要查看),您可以通过以下方式检查用户是否为管理员:
user.admin? # true if admin, false otherwise

您可以对所有角色执行相同操作(查看提供的文档以获得更全面的解释): user.client? # true if client, false otherwise user.seller? # true if seller, false otherwise

最后要注意的是,如果您的列中包含default: 0,则enum列表中的第一项将成为默认角色,在本例中为client。在创建新用户时,您需要牢记这一点。

最后,文档:http://api.rubyonrails.org/v5.1.0/classes/ActiveRecord/Enum.html

相关问题