Ruby on Rails 全球 ActiveRecord::Enum

19 浏览
0 Comments

Ruby on Rails 全球 ActiveRecord::Enum

我真的很喜欢Rails 4的新枚举功能,但是我想在每个模型中使用我的枚举

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

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

我非常新手,需要你的帮助找到解决方案

admin 更改状态以发布 2023年5月21日
0
0 Comments

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

# 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

0
0 Comments

使用ActiveSupport :: Concern,这个功能被创建来使模型代码更加干燥:

#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

阅读更多

0