Reputation: 8730
I want to use enum
on existing date.
There is column status
in table containing thousands of records.
Issue is that records in my db are in capital like Active,Pending,Awaiting Review,Closed etc
Now I define an enum
enum status: [:active,:closed,:pending,:awaiting_review]
How its not working due to capital reason and underscore instead of space.
When I do Model.first.status
it return nil
Upvotes: 0
Views: 703
Reputation: 17834
Your issue is, you are trying to do this Model.status
, it won't return anything, because status
is an instance method, not class method, if you want to see all the statuses, do this
Model.statuses
It returns a hash, if you want to fetch status of a Model object, here's an example
Model.first.status
And, by default, enum expects an integer column, so if you define enum like this
enum status: [:active,:closed,:pending,:awaiting_review]
Then, the value in table would be 0, 1, 2, 3
for each respectively.
So you might want to migrate status
column to integer
and then write a rake task to update the existing values to the new ones according to the enum values!
In your case, you say awaiting_review
is returning nil because your existing value was awaiting review
, i.e., without the underscore. For a quick fix, define this method in your model
def status
if self.read_attribute_before_type_cast(:status) == 'Awaiting Review'
'Awaiting Review'
else
super
end
end
To use the above approach for every case, define your enum like this instead
enum status: { active: 'active', closed: 'closed', pending: 'pending', awaiting_review: 'Awaiting Review' }
Change the string hash values according to what is saved in your table
Hope that helps
Upvotes: 1