Hommer Smith
Hommer Smith

Reputation: 27852

Rails - drop down from an array of strings

I have an array like this:

['New York', 'Los Angeles']

And I want to be able to generate a select/option with those values in a form like this:

<%= form_tag filter_city_path, :method=> get do %>
  <%= select_tag "city", @list_of_cities %>
<% end %>

But this is not working. As you can see I want to pass the selection as city in the url.

Upvotes: 12

Views: 14102

Answers (3)

Jeremy
Jeremy

Reputation: 675

My method for this is to build the array as a constant in the model, force confirmation to options listed in the constant, and call it from the view

class Show < ApplicationRecord

  DAYS = [ "monday", "tuesday", "wednesday", "thursday","friday", "saturday","sunday"]

  validates :day, inclusion: DAYS

end

If you want the option for that field to be submitted without content you'll have to call `allow_blank: true' in the validation as well. Once that is set up you can call the constant to populate the view in the form as so:

<%= select_tag "day", options_for_select(Show::DAYS) %>

or

<%= select_tag "day", options_for_select(Show::DAYS.sort) %>

if you want it presorted (which makes no sense with days of the week...)

Upvotes: 6

naren
naren

Reputation: 937

You need to use options_for_select helper like

<%= select_tag "city", options_for_select([['New York' ,'New york'], ['Los Angeles', 'Los Angeles']]) %>

Upvotes: 19

Victor
Victor

Reputation: 13378

It looks like your array doesn't have enough argument. Please refer to this guide.

The options typically needs to be formatted in this way:

[['Lisbon', 1], ['Madrid', 2], ...]

Take note the value 1, 2, etc.

Upvotes: 0

Related Questions