Harry
Harry

Reputation: 1699

Rails store key value for a select input

I have in my .html.erb:

 <label for="form_marital_status">Marital Status:</label>
 <%= select("form", "marital_status", marital_status_options, {}, { }) %>

Where marital_status_options is defined in my helper as:

 def marital_status_options
      %w[Select Single Married Common-Law/Partner Divorced Widowed]
 end

Is there a way I can define marital_status_options to have a key value pairing for use in the select?

Upvotes: 1

Views: 3512

Answers (1)

deefour
deefour

Reputation: 35370

%w[Select Single Married Common-Law/Partner Divorced Widowed]

This is going to make the option value and text for each option the same. Return an array of arrays if you want the option value and text to be different for each option. The first value in each array is the text value for the option; the second is the option value itself.

def marital_status_options
  [["Select", ""], ["Single", "single"], ["Married", "married"], ["Common-Law/Partner", "partners"], ["Divorced", "divorced"], ["Widowed", "widowed"]] 
end

This is explained clearly in the documentation.

You should also consider not passing the blank "Select" option from your method as there is a way to do this through the select method itself.

# Helper
def marital_status_options
  [["Single", "single"], ["Married", "married"], ["Common-Law/Partner", "partners"], ["Divorced", "divorced"], ["Widowed", "widowed"]] 
end

# form
<%= select("form", "marital_status", marital_status_options, {:include_blank => "Select"}) %>

Upvotes: 4

Related Questions