2

I have a select option in a form:

<%= f.select :role, options_for_select(User.roles.keys.to_a, params[:role]), {}, class: 'form-control form-control-lg roleSelect' %>

These roles are defined in my model:

enum role: {user: 0, profile_user: 1}

Now in my dropdown when the user choses it shows user and profile_user as drop down option.

Is there any way to show another value to represent these in a drop down?

For example:

In the drop down I would rather show "I am a teacher" which maps to user.

In the drop down I would rather show "I am here to study" which maps to profile_user.

Gurmukh Singh
  • 1,875
  • 3
  • 24
  • 62
  • Possible duplicate of [Saving enum from select in Rails 4.1](https://stackoverflow.com/questions/23686265/saving-enum-from-select-in-rails-4-1) – Josh Brody Jan 06 '18 at 21:54

1 Answers1

2

In your model add your narrative descriptions.

NARRATIVE_ROLES = {user: 'I am a teacher', profile_user: 'I am here to learn'}

Add a method to create the select_array

def self.roles_select
  User.roles.keys.map {|role| [NARRATIVE_ROLES[role], role]}
end

Then in the select you use

options_for_select(User.roles_select, params[:role])

Or (slightly simpler)

NARRATIVE_ROLES = {'I am a teacher' => :user, 'I am here to learn' => :profile_user}

options_for_select(User::NARRATIVE_ROLES, params[:role])
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53