Reputation: 8730
All these enums are not added in diff columns.
My model:
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]
It returns the following error:
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
How can I fix it?
Upvotes: 4
Views: 2059
Reputation: 46389
For Rails 4, you can backport prefix and suffix support from the current implementation. Worked for me, but use at your own risk!
Simply copy this to config/initialisers/enum.rb (or anywhere else that will be processed during server boot, e.g. a lib file if you add it to your path). That's the raw source from the Rails 5 enum implementation.
Upvotes: 4
Reputation: 12320
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.
enum gender: [:Male, :Female,:All], _prefix: :gender
enum qualification: [:Uneducated,:Matric, :Inter, :Graduation, :Masters, :PHD,:All], _suffix: true
Now you can access user.gender_Male!
and user.Matric_qualification!
or
user.gender_Male?
and user.Matric_qualification?
Upvotes: 1
Reputation: 76774
How I fix it?
Don't include :all
in your enum
's, set a different value OR use a prefix/suffix:
enum gender: [:male, :female, :both]
If you look at their docs, you'll see that you can have a suffix or prefix:
enum gender: [:male, :female, :both], _prefix: :gender
This will give you:
@object.gender_male?
@object.gender_female?
@object.gender_both?
The reason why you're getting the error is because the enum
class adds instance methods for the various options in your enum
.
This normally works fine, but if you have multiple enum
's with the same value inside, the model simply won't be able to handle the different instance methods, hence your error.
Upvotes: 6