2011-05-25 81 views
1

我有一个用户模型,我想要一个user_status属性。用户状态字段,如何映射到枚举

我想要这个属性作为整数存储在数据库中。

我就在想,然后创建一个枚举,然后该枚举映射到整数值,所以我可以做这样的事情的:

if user.status == MyEnum::RequiresApproval 
.. 
.. 

使用active_record,在模型级,是有什么我可以做与枚举?

在这种情况下通常会做什么?

回答

2

枚举不像Rails那样。状态机是。

时退房“过渡”宝石(link)(这几乎是Rails核心的一部分)

然后你就可以执行下列操作...

#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 

这对我是一个过渡也不使用枚举和类型表 - 但我没有错过它们

+0

这将与mongoid一起工作吗? – Blankman 2011-05-25 15:24:12

+0

当然可以 - 我使用的代码来自Mongoid模型(mongoid是最好的!) – Jonathan 2011-05-25 15:32:15