我有一個形式的下列:顯示文本表示導軌
<div class="col-sm-2 form-group">
<%= f.label :from_age, "From Age" %><br>
<%= f.select :from_age, [*-1..65], {}, class: "form-control" %>
</div>
<div class="col-sm-2 form-group">
<%= f.label :to_age, "To Age" %><br>
<%= f.select :to_age, [*-1..65] << 1000, {}, class: "form-control" %>
</div>
換句話說:
對於from_age
,用戶選擇之間的年齡數字-1到65. -1代表「全部」的概念。
對於to_age
,用戶選擇數字-1到65之間的年齡,也可以選擇數字1000. -1代表「全部」的概念,1000代表「和上」的概念。
隨着from_age
和to_age
規定,該應用程序現在可以說:
- 一個機構提供
All
時代 - 一個機構提供一個年齡的人
18 and up
- 年齡
25-40
的代理服務的個人的個人
創建新代理時,上面的代碼w orks ok,但用戶需要知道值-1
代表up
,而值1000
代表值and up
。
我可以做得更好。我只需要在選擇框中顯示錶示值的文本,因此在選擇框內:而不是看到-1
用戶看到:All
,而不是1000
用戶看到:and up
。
我有我的Agency
模型如下:
def from_age_to_s
if from_age == -1
return "All"
else
return from_age
end
end
def to_age_to_s
case to_age
when -1
"All"
when 1000
"+up"
else
to_age
end
end
所以基本上我需要告訴的形式:「是的,這些都是價值觀和正確的,但對於那些值顯示的文本,利用這些方法,表示打通的形式傳遞這些價值的文本。
Documentation on select form helper。在這種情況下
也許是更好地使用collection_select?
更新:
多虧了下面的答案提供幫助。這裏是我的from_age
解決方案:
<div class="col-sm-2 form-group">
<%= f.label :from_age, "From Age" %><br>
<%= f.select :from_age, options_for_from_date, {}, class: "form-control" %>
</div>
# helpers/application_helper.rb
def options_for_agencies_from_date
[ [ 'All', -1 ], *0..65]
end
def options_for_agencies_to_date
[ [ 'All', -1 ], *0..65, [ '+up', 1000 ] ]
end
不要做'[* -1..65]'。 Range對象響應'map';你不需要先將它轉換成一個數組。只要做'(-1..65).map'。 (如果你想將Range轉換爲數組,只需使用'.to_a',即'(-1..65).to_a')。 –
我已經更新了我的答案並略有改進:您不需要執行'[num,num]'事情。 –
@Jordan超級光滑!我更新了問題中的更新。謝謝!! – Neil