繁体   English   中英

Ruby on Rails Global ActiveRecord :: Enum

[英]Ruby on Rails Global ActiveRecord::Enum

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

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

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

我是Ruby on Rails新手,需要你的帮助才能找到解决方案

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

我认为您可以使用包含此枚举的模块,然后您可以在要使用的每个模块中包含:

# 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM