For the sake of quick documentation of a common use case.
If you have a model, which has an enum attribute and you want to have a select tag(dropdown) with titleized values(no ugly underscores) of the enum and you also want to store the data in its original(enum form).
Here's a quick example
# app/models/source.rb
class Vendor < ApplicationRecord
# in the db schema, vendors table has payment_type column with integer datatype(the datatype can be different, no issues)
enum payment_type: [:one_time :recurring :not_known]
end
Then in your view file, where you want to display the dropdown for that enum attribute
<%= form_with(model: @vendor, local: true) do |form| %>
<%= form.label :payment_type %>
<%= form.select :payment_type, options_for_select(Vendor.payment_types.map {|key, value| [key.titleize, Vendor.payment_types.key(value)]}, @vendor.payment_type) %>
<%= form.submit %>
<% end %>
That's all.
With this done, your dropdown will display three options with the text
One Time
, Recurring
, and Not Known
while when you submit the form the submitted value of payment_type
will be
one_time
or recurring
or not_known
depending on which option you selected from the dropdown.
Top comments (4)
You can also use translate_enum gem; github.com/shlima/translate_enum
thanks for pointing it out. It's indeed useful.
Nice.
Many thanks