我有一个这样的数组:
['New York', 'Los Angeles']
我希望能够以这样的形式生成带有这些值的select /选项:
<%= form_tag filter_city_path, :method=> get do %>
<%= select_tag "city", @list_of_cities %>
<% end %>
但这不起作用。如您所见,我想在网址中将选择作为城市传递。
答案 0 :(得分:15)
您需要使用options_for_select helper,如
<%= select_tag "city", options_for_select([['New York' ,'New york'], ['Los Angeles', 'Los Angeles']]) %>
答案 1 :(得分:1)
我的方法是在模型中将数组构建为常量,强制确认常量中列出的选项,并从视图中调用它
class Show < ApplicationRecord
DAYS = [ "monday", "tuesday", "wednesday", "thursday","friday", "saturday","sunday"]
validates :day, inclusion: DAYS
end
如果您希望在没有内容的情况下提交该字段的选项,则必须调用`allow_blank:true&#39;在验证中也是如此。设置完成后,您可以调用常量来填充表单中的视图,如下所示:
<%= select_tag "day", options_for_select(Show::DAYS) %>
或
<%= select_tag "day", options_for_select(Show::DAYS.sort) %>
如果你想要它预先排序(这对一周中的几天没有意义......)
答案 2 :(得分:0)