共享具有多个属性的枚举声明值 [英] Share enum declaration values with multiple attributes
问题描述
我想要一个具有多个属性的类,用数值保存工作日.
I want to have a class with several attributes that saves weekdays with numeric values.
summary_weekday :integer
collection_weekday :integer
我想我可以将整数映射到值 使用 Enum 和两个声明:
I thought I could map the integers to values using Enum with two declarations:
enum summary_weekday: %w(monday tuesday wednesday thursday friday saturday sunday)
enum collection_weekday: %w(monday tuesday wednesday thursday friday saturday sunday)
但是 Rails 不接受,我不能在同一个类中定义相同的值两次.
But Rails doesn't accept that, I cannot define the same value twice in the same class.
您试图在模型上定义一个名为summary_weekday"的枚举QuestionCategory",但这会生成一个实例方法星期一?",它已经由另一个枚举定义.
You tried to define an enum named "summary_weekday" on the model "QuestionCategory", but this will generate a instance method "monday?", which is already defined by another enum.
我该如何解决这个问题?
How can I solve this?
推荐答案
从 Rails 5.0 开始,当您需要定义多个枚举时,您可以使用 _prefix
或 _suffix
选项具有相同的值.如果传递的值为 true,则方法以枚举的名称作为前缀/后缀.
As of Rails 5.0 you can use the _prefix
or _suffix
options when you need to define multiple enums with same values. If the passed value is true, the methods are prefixed/suffixed with the name of the enum.
class Invoice < ActiveRecord::Base
enum verification: [:done, :fail], _prefix: true
end
也可以提供自定义前缀.
It is also possible to supply a custom prefix.
class Invoice < ActiveRecord::Base
enum verification: [:done, :fail], _prefix: :verification_status
end
这篇关于共享具有多个属性的枚举声明值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!