Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
Hommer Smith Avatar asked Apr 24 '12 01:04

Hommer Smith


2 Answers

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

like image 57
Jeremy Avatar answered Oct 14 '22 00:10

Jeremy


You need to use options_for_select helper like

<%= select_tag "city", options_for_select([['New York' ,'New york'], ['Los Angeles', 'Los Angeles']]) %>
like image 35
naren Avatar answered Oct 13 '22 22:10

naren