我有一个这样的数组:Rails的 - 从字符串数组下拉
['New York', 'Los Angeles']
而且我希望能够产生与这些值的形式这样的选择/选项:
<%= form_tag filter_city_path, :method=> get do %>
<%= select_tag "city", @list_of_cities %>
<% end %>
但是这不起作用。正如你所看到的,我想通过URL为城市。
我有一个这样的数组:Rails的 - 从字符串数组下拉
['New York', 'Los Angeles']
而且我希望能够产生与这些值的形式这样的选择/选项:
<%= form_tag filter_city_path, :method=> get do %>
<%= select_tag "city", @list_of_cities %>
<% end %>
但是这不起作用。正如你所看到的,我想通过URL为城市。
您需要使用options_for_select帮手像
<%= select_tag "city", options_for_select([['New York' ,'New york'], ['Los Angeles', 'Los Angeles']]) %>
我的方法是在模型中将数组构建为常量,并强制确认常量中列出的选项,然后从中调用它视图
class Show < ApplicationRecord
DAYS = [ "monday", "tuesday", "wednesday", "thursday","friday", "saturday","sunday"]
validates :day, inclusion: DAYS
end
如果你想如果没有内容将提交该字段的选项,你就必须调用`allow_blank:真正的”在验证为好。一旦建立,你可以调用常量来填充表单视图像这样:
<%= select_tag "day", options_for_select(Show::DAYS) %>
或
<%= select_tag "day", options_for_select(Show::DAYS.sort) %>
如果你想预拣(这是没有意义的为期一周的日子...)
只要有可能,尝试以编程方式转换您的数组,而不是将它们拼写出来。你已经说明了为什么不在第二次使用“约克”时。 'cities.collect {| c | [c,c]}会做扩大它的工作。 – tadman 2012-04-24 03:01:44