所有这些枚举都没有添加到差异列中。
我的模特:
enum relationship_status: [:Married, :Single, :Engaged, :Divorced, :Widowed, :Separated, :Complicated,:All]
enum gender: [:Male, :Female,:All]
enum qualification: [:Uneducated,:Matric, :Inter, :Graduation, :Masters, :PHD,:All]
它返回以下错误:
You tried to define an enum named "gender" on the model "Campaign", but this will generate a instance method "All?", which is already defined by another enum
我该如何解决?
答案 0 :(得分:4)
我如何解决?
请勿在{{1}}中添加:all
,设置不同的值或使用前缀/后缀:
enum
如果您查看他们的docs,您会发现自己可以拥有suffix or prefix:
enum gender: [:male, :female, :both]
这会给你:
enum gender: [:male, :female, :both], _prefix: :gender
您收到错误的原因是@object.gender_male?
@object.gender_female?
@object.gender_both?
类为enum
中的各种选项添加了实例方法。
这通常可以正常工作,但是如果你有多个enum
的内部具有相同的值,那么模型将无法处理不同的实例方法,因此会出错。
答案 1 :(得分:4)
对于Rails 4,您可以从当前实现中支持前缀和后缀支持。为我工作,但使用风险自负!
只需copy this来配置/初始化/ enum.rb(或在服务器启动期间将处理的任何其他地方,例如,如果将其添加到路径中,则为lib文件)。这是the Rails 5 enum implementation的原始来源。
答案 2 :(得分:1)
当您需要定义具有相同值的多个枚举时,可以使用_prefix or _suffix
选项。如果传递的值为true,则方法为prefixed/suffixed
,其名称为枚举。
enum gender: [:Male, :Female,:All], _prefix: :gender
enum qualification: [:Uneducated,:Matric, :Inter, :Graduation, :Masters, :PHD,:All], _suffix: true
现在您可以访问user.gender_Male!
和user.Matric_qualification!
或
user.gender_Male?
和user.Matric_qualification?