2014-09-19 117 views
3

我真的很喜歡Rails的4個新的枚舉功能,但我想用我的枚舉Ruby on Rails的ActiveRecord的全球枚舉::

enum status: [:active, :inactive, :deleted]

在每一個模型。我找不到任何方式如何聲明例如在config/initializes/enums.rb,包括每一個模型

我在Ruby on Rails非常新的,需要你的幫助,以找到解決

回答

17

使用ActiveSupport::Concerndry創造了這個功能,荷蘭國際集團後續機型代碼:

#app/models/concerns/my_enums.rb 
module MyEnums 
    extend ActiveSupport::Concern 

    included do 
    enum status: [:active, :inactive, :deleted] 
    end 
end 

# app/models/my_model.rb 
class MyModel < ActiveRecord::Base 
    include MyEnums 
end 

# app/models/other_model.rb 
class OtherModel 
    include MyEnums 
end 

Read more

+0

坦克綠人保存我的日子:) – 2014-09-19 16:06:44

+0

@IrakliLekishvili我的榮幸! – 2014-09-19 16:07:09

+0

很棒的回答。我也發現[這個問題和答案](http://stackoverflow.com/questions/14541823/how-to-use-concerns-in-rails-4)有幫助。 – 2015-09-08 21:32:05

0

我認爲你可以使用一個包含該枚舉則一個模塊您可以包括每個模塊中要使用:

# app/models/my_enums.rb 
Module MyEnums 
    enum status: [:active, :inactive, :deleted] 
end 

# app/models/my_model.rb 
class MyModel < ActiveRecord::Base 
    include MyEnums 
end 

# app/models/other_model.rb 
class OtherModel 
    include MyEnums 
end 
+1

它不會工作,因爲枚舉是在ActiveRecord :: Enum中定義的。所以我得到這個錯誤:'':未定義的方法enum'MyEnums:Module(NoMethodError) – 2014-09-19 15:47:05

+1

'enum'類宏只能在'ActiveRecord'中使用。 – 2014-09-19 15:55:19

相關問題