[英]Ruby on Rails Global ActiveRecord::Enum
我真的很喜歡Rails 4新的Enum功能,但我想使用我的枚舉
enum status: [:active, :inactive, :deleted]
在每個模型中。 我找不到任何方法如何在config/initializes/enums.rb
並包含每個模型
我是Ruby on Rails
新手,需要你的幫助才能找到解決方案
使用ActiveSupport::Concern
為dry
模型代碼而創建的此功能:
#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
我認為您可以使用包含此枚舉的模塊,然后您可以在要使用的每個模塊中包含:
# 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.