Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same enum not working in different columns in rails

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?

like image 991
Haseeb Ahmad Avatar asked Dec 19 '22 21:12

Haseeb Ahmad


1 Answers

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.

like image 179
Richard Peck Avatar answered Dec 27 '22 15:12

Richard Peck