Ruby on Rails Global ActiveRecord :: Enum

时间:2014-09-19 15:22:02

标签: ruby-on-rails ruby ruby-on-rails-4 enums

我非常喜欢Rails 4新的Enum功能,但我想使用我的枚举

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

在每个模型中。我找不到任何方法如何在config/initializes/enums.rb中声明并包含每个模型

我在Ruby on Rails中非常新,需要您的帮助才能找到解决方案

2 个答案:

答案 0 :(得分:20)

使用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

答案 1 :(得分: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