RoR select_tag默认值和选项
如何使用select_tag
设置默认值,以及如何在页面加载时保持打开选项?
如果你使用select_tag
没有任何其他的帮手,那么你可以在html中做到这一点:
select_tag "whatever", "<option>VISA</option><option selected=\"selected\">MasterCard</option>"
或者用options_for_select
:
select_tag "whatever", options_for_select([ "VISA", "MasterCard" ], "MasterCard")
或者用options_from_collection_for_select
:
select_tag "people", options_from_collection_for_select(@people, 'id', 'name', '1')
示例来自select_tag
doc , options_for_select
doc和options_from_collection_for_select
doc 。
对于options_for_select
<%= select_tag("products_per_page", options_for_select([["20",20],["50",50],["100",100]],params[:per_page].to_i),{:name => "products_per_page"} ) %>
用于select集合的选项
<%= select_tag "category","<option value=''>Category</option>" + options_from_collection_for_select(@store_categories, "id", "name",params[:category].to_i)%>
请注意,您指定的选定值必须是types值。 即如果值是整数格式,那么select的值参数也应该是整数。
另一种select(如果你需要添加数据属性或其他)
= content_tag(:select) do - for a in array option data-url=a.url selected=(a.value == true) a.name
它已经解释了,将试图举一个例子,实现相同的没有options_for_select
让select列表
select_list = { eligible: 1, ineligible: 0 }
所以下面的代码结果
<%= f.select :to_vote, select_list %> <select name="to_vote" id="to_vote"> <option value="1">eligible</option> <option value="0">ineligible</option> </select>
所以为了使选项默认选中,我们必须使用selected:value 。
<%= f.select :to_vote, select_list, selected: select_list.can_vote? ? 1 : 0 %>
如果can_vote? 返回true它设置select:1然后第一个值将被选中其他秒。
select name="driver[bca_aw_eligible]" id="driver_bca_aw_eligible"> <option value="1">eligible</option> <option selected="selected" value="0">ineligible</option> </select>
如果select选项只是一个数组列表而不是hast,那么选中的将只是要select的值,例如if
select_list = [ 'eligible', 'ineligible' ]
现在select将采取
<%= f.select :to_vote, select_list, selected: 'ineligible' %>