Kyle Bachan
Kyle Bachan

Reputation: 1107

How to get the index of a selected dropdown item in a Rails form

How would I get the index number of the dropdown selection that the user picks from the form's fields? I would like to be able to save this index number to the Rails database.

= simple_form_for(Rule.new, html: {:multipart => true, autocomplete: "off", :class=> "form-horizontal" }, remote: true, :authenticity_token => true) do |f|
    = f.select :header, @headers.each{|header|}, {:prompt   => "Select a Header"}, {id: "ruleHeader_select"}
    br
    = f.collection_select(:rule_type_id,  @ruleTypes, :id, :name, {:prompt   => "Select a Rule Type"}, {:id => 'ruleTypes_select', style: "display:none;"})
    = f.button :submit

Upvotes: 0

Views: 211

Answers (1)

fivedigit
fivedigit

Reputation: 18682

You can pass an array of arrays as options into collection_select:

@ruleTypes.each_with_index.to_a

This will show the values from @ruleTypes to the user, while the selected values will be indexes.

Upvotes: 1

Related Questions