Home Rails select values
Reply: 1

Rails select values

Gurmukh Singh
Gurmukh Singh Published in 2018-01-06 20:54:20Z

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.

SteveTurczyn Reply to 2018-01-06 22:49:27Z

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]}

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])
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.313452 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO