2011-05-25 30 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