【发布时间】:2016-10-18 21:44:00
【问题描述】:
我在标准 ruby on rails 表单中有一个选择器。选择器适用于国家,而分隔符为大洲。但我不想硬编码国家的值。我从控制器返回几个国家列表(每个大陆一个)。我想把它放在那里而不是硬编码数组。
我有什么:
HTML
<% grouped_options = [['North America',['USA','Mexico']],['Europe',['Denmark','Germany','France']]] %>
<%= f.select :country_id, grouped_options_for_select(grouped_options), {:include_blank => "Please select a country"}, {:required => true, :class => "white_background"} %>
我想要什么:
<% grouped_options = [['North America',@north_america_names],['Europe',@europe_names]] %>
编辑: 此选项不起作用,我不确定为什么?
控制器
@north_america_names = Country.select(:name, :id).where("continent = 'North America').distinct
@europe_names = Country.select(:name, :id).where("continent = 'Europe').distinct
控制器工作得很好,它返回一个名称和 ID 列表。
编辑 2:
这是我以前的(没有分隔线),效果也很好。
HTML
<%= f.collection_select(:country, @country_list, :id, :name, {:include_blank => "Please select a country"}, {:required => true, :class => "white_background"}) %>
控制器
@country_list = Country.select(:name, :id).all
【问题讨论】:
-
你的问题是什么?
-
哦,对了,我的问题是如何使第二个选项起作用。它似乎只是插入对象引用,而不是名称。
-
您可能需要
to_a将 activerecord 查询对象转换为数组。@north_america_names.to_a -
我尝试了 .to_a ,它似乎对选择中显示的内容没有任何影响。
标签: html ruby-on-rails ruby ruby-on-rails-3