Tamik Soziev
Tamik Soziev

Reputation: 14798

Ruby on Rails: create a hash for select menu from array

I have an array:

@positions = ["external_footer", "external_top_menu", "external_side_menu"]

I want to create a select box so it produces humanized value for option and original value for option value. So i want something like that:

<option value="external_footer">External Footer</option>

Right now i am doing it like so:

= f.input :position, collection: @positions.collect{|position| { position => position.humanize}}

But it does not work.

Upvotes: 0

Views: 1812

Answers (3)

Bad Request
Bad Request

Reputation: 4040

First of all, your syntax may be wrong - you have one extra pair of braces. Try = f.input :position, collection: @positions.collect{|position| position.humanize} or = f.input :position, collection: @positions.collect(&:humanize)

Assuming you're using SimpleForm, it's possible it doesn't know what method to call for the option label and value. Try passing the :label_method and :value_method explicitly, or pass humanize as a lambda, as described here.

Upvotes: 0

Tamik Soziev
Tamik Soziev

Reputation: 14798

I found a solution:

= f.input :position, collection: @positions.collect{|p| [ p.humanize, p ] }

Upvotes: 3

Thanh
Thanh

Reputation: 8604

Do you have a @positions in your controller? , if not, i think you should change:

positions = ["external_footer", "external_top_menu", "external_side_menu"]

to:

@positions = ["external_footer", "external_top_menu", "external_side_menu"]

And you can try this:

= f.input :position, collection: @positions.collect { |position| position.humanize }

Upvotes: 0

Related Questions