[英]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: 我希望能够以这样的形式生成带有这些值的select /选项:
<%= 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. 如果您希望在没有内容的情况下提交该字段的选项,您还必须在验证中调用“allow_blank:true”。 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. 注意值为1
, 2
,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.