12

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.

3 Answers 3

19

You need to use options_for_select helper like

<%= select_tag "city", options_for_select([['New York' ,'New york'], ['Los Angeles', 'Los Angeles']]) %>
Sign up to request clarification or add additional context in comments.

1 Comment

Whenever possible, try and programmatically transform your arrays instead of spelling them out long-hand. You've illustrated why when not capitalizing 'york' in the second instance. cities.collect { |c| [ c, c ] } would do the job of expanding it.
6

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...)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.