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.
你需要使用options_for_select helper之类的
<%= select_tag "city", options_for_select([['New York' ,'New york'], ['Los Angeles', 'Los Angeles']]) %>
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...)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.