Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify text displayed in simple_form input when using enum

I'm using simple_form for managing my users. For selecting the user role I use input as: :radio_button.

The collection come from a enum on the user model. How can I modify the text to show something specific like "Super Admin" instead of super_admin?

_form.html.slim

= form.input :role, collection: User.roles, as: :radio_buttons, item_wrapper_class: 'btn btn-default', checked: User.roles[user.role], required: true

user.rb

  enum role: [:super_admin, :admin, :generic]
like image 268
Antarr Byrd Avatar asked Sep 21 '15 19:09

Antarr Byrd


2 Answers

you can use the label_method option with the collection

= form.input :role, collection: User.roles, label_method: lambda {|k| k.humanize}, as: :radio_buttons, item_wrapper_class: 'btn btn-default', checked: User.roles[user.role], required: true
like image 99
bigsolom Avatar answered Nov 18 '22 16:11

bigsolom


If you want to do something more complex than calling a method on the key, Simple Form has support for translating collection options with I18n - you just have to provide the collection as an array of symbols for the lookup to work.

Here's what worked for me on SimpleForm 3.5.0:

Locale file:

en:
  simple_form:
    options:
      user:
        role:
          super_admin: 'Super Admin'
          admin: 'Admin'
          generic: 'Regular Joe'

View:

<%= f.input :role, collection: User.roles.symbolize_keys.keys %>
like image 25
Jared Avatar answered Nov 18 '22 18:11

Jared