towlie
towlie

Reputation: 21

Ruby-on-Rails: Can enum value be a string. Where is this documented?

Can someone point me to some ROR documentation that describes setting the value of an enum as a string? All the documentation and examples I've found seem to indicate that the value should be an integer. However I am able to create an enum with string values, use it in view and save it to the database without any issues. I would really like to find out more on this topic.

Example that works

Set in ModelName

enum category_enum: { 'abc efg'=> 'alpha', 'hot dog' => 'bun' }

Set in view

<%= f.select :category, ModelName.category_enums %>

Upvotes: 2

Views: 1736

Answers (1)

Eliot Sykes
Eliot Sykes

Reputation: 10063

I didn't find any documentation and didn't confirm the behaviour myself, however a pull request was merged into Rails in November 2013 and the description from the contributor Yury is:

Allow to pass explicit mapping values to enum...I don't strict values to integers, so if needed, strings can be used. (source: https://github.com/rails/rails/pull/12747)

So it appears this is indeed supported.

Upvotes: 1

Related Questions