Search code examples
ruby-on-railsenumssimple-form

Enum, how to display multiple word in simple_form?


I'm using enum for :discount_type. The enum is either percent or price.

For clarity purposes I would like to show price per day in my simple_form for the enum price. How can I do this?

Code

model

enum discount_type: { percent: 1, price: 0 }

form

<%= f.input :discount_type, collection: ['percent', 'price'] %>

previous attempt

model
enum discount_type: { percent: 1, price_per_day: 0 }

form
<%= f.input :discount_type, collection: ['percent', 'price per day'] %>

error message:
==> 'price per day' is not a valid discount_type

Solution

  • From the docs:

    The mappings are exposed through a class method with the pluralized attribute name, which returns the mapping in a HashWithIndifferentAccess...

    This is a bit ugly, because of the per day addition to price:

    Model.discount_types.transform_keys { |key| key == 'price' ? 'price per day' : key }.keys
    # ["percent", "price per day"]
    

    So, in your form:

    <%= f.input :discount_type, collection: Model.discount_types.transform_keys { |key| key == 'price' ? 'price per day' : key }.keys %>