標籤:rate number 方便 select cto upd enum method stat
enum的作用是聲名一個枚舉屬性來映射資料庫裡整型欄位的值,並能通過這個屬性來查詢資料庫。
可以這麼使用(案例來自官方),比如:
class Conversation < ActiveRecord::Base enum status: [ :active, :archived ]end
或者
class Conversation < ActiveRecord::Base enum status: { active: 0, archived: 1 }end
# conversation.update! status: 0conversation.active!conversation.active? # => trueconversation.status # => "active"# conversation.update! status: 1conversation.archived!conversation.archived? # => trueconversation.status # => "archived"# conversation.status = 1conversation.status = "archived"conversation.status = nilconversation.status.nil? # => trueconversation.status # => nil
關於查詢的:
Conversation.where(status: [:active, :archived])Conversation.where.not(status: :active)
這樣使用很方便,但是使用這個enum時候一定要非常注意,你可能注意到了,它會產生一些方法。比如上面,它產生了:active!
,active?
,status= 等等。
如果你一不小心使用了:group屬性,比如這樣定義:
class Conversation < ActiveRecord::Base enum status: {group: 0, single: 1}end
運行時它會產生You tried to define an enum named "statuss" on the model "ConfirmAsset", but this will generate a class method "group", which is already defined by Active Record.這樣的錯誤。
另外使用欄位名稱的時候也要注意,因為我得到了這樣的錯誤:You tried to define an enum named "import" on the model "ConfirmAsset", but this will generate a instance method "import=", which is already defined by another enum.
ruby on rails 在model中使用enum的注意事項