使用simple_form选择值的数字范围

时间:2012-12-04 12:06:34

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 simple-form

我选择了simple_form:

<%= f.input :theme, :collection => ["#{t('.text_1')}", "#{t('.text_2')}", "#{t('.text_3')}", "#{t('.text_4')}", :value_method => lambda { |n| n } %>

html是:

<select class="select required" id="inquiry_theme" name="inquiry[theme]"><option value="">Choose a topic related to your query</option>
<option value="Text1">Text1</option>
<option value="Text2">Text2</option>
<option value="Text3">Text3</option>
<option value="Text4">Text4</option>

我希望使用范围编号设置值,而不是文本,例如:

<select class="select required" id="inquiry_theme" name="inquiry[theme]"><option value="">Choose a topic related to your query</option>
<option value="1">Text1</option>
<option value="2">Text2</option>
<option value="3">Text3</option>
<option value="4">Text4</option>

可以使用:value_method中的lambda

谢谢!

2 个答案:

答案 0 :(得分:5)

考虑到你的例子,我认为使用value_method有点矫枉过正。

<%= f.input :theme, :collection => [[1, "#{t('.text_1')}"], [2, "#{t('.text_2')}"], [3, "#{t('.text_3')}"], [4, "#{t('.text_4')}"]] %>

虽然我把它写成

<%= f.input :theme, :collection: (1..4).map { |i| [i, t(".text_#{i}")] }.unshift([nil, 'Choose a topic related to your query'] %>

答案 1 :(得分:2)

根据您的示例输出,我这样写,它可能对您有用。

<%= f.select :theme,options_for_select((1..4).to_a.map{|x| [x,"Text#{x}"]}.insert(0, "Choose a topic related to your query")) ,:id=>"inquiry_theme" %>