用户状态字段,如何映射到枚举

问题描述

| 我有一个用户模型,我想有一个user_status属性。 我希望此属性数据库中存储为整数。 我当时正在考虑创建一个枚举,然后将该枚举映射到整数值,这样我就可以执行以下操作:
if user.status == MyEnum::RequiresApproval
..
..
在模型级别使用active_record,我可以对枚举做些事情吗? 在这种情况下通常会做什么?     

解决方法

枚举不是很像Rails。状态机。 查看\'transitions \'gem(链接)(这几乎是Rails Core的一部分) 然后您可以执行以下操作...
 #GemFile
 gem \"transitions\",:require => [\"transitions\",\"active_record/transitions\"]


 #And in your Model,do something like the following:
  include ActiveRecord::Transitions

  field :state,type: String
  scope :active,where(state: \'active\')

  state_machine do
    state :active
    state :inactive

    event :inactivate do
      transitions :from => :active,:to => :inactive
    end

    event :activate do
      transitions :from => :inactive,:to => :active
    end
  end
对我来说,这也是一个过渡,不使用枚举和类型表-但是我没有错过它们