RoR select_tag默认值&选项

时间:2010-08-03 11:30:47

标签: ruby-on-rails

如何使用select_tag设置默认值,如何在页面加载时保持选项打开?

5 个答案:

答案 0 :(得分:106)

如果您使用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 [SELECT_FIELD_NAME], options_from_collection_for_select([YOUR_COLLECTION], [NAME_OF_ATTRIBUTE_TO_SEND], [NAME_OF_ATTRIBUTE_SEEN_BY_USER], [DEFAULT_VALUE])

示例:

select_tag "people", options_from_collection_for_select(@people, 'id', 'name', '1')

示例来自select_tag docoptions_for_select docoptions_from_collection_for_select doc

答案 1 :(得分:2)

对于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_tag "category","<option value=''>Category</option>" +  options_from_collection_for_select(@store_categories, "id", "name",params[:category].to_i)%>

请注意,您指定的选定值必须是value类型。   即如果值为整数格式,则所选值参数也应为整数。

答案 2 :(得分:2)

试试这个:

<%= select_tag(:option, options_for_select([["Option 1",1],["Option 2",2],["Option 3",3]], params[:option] ), class:"select") %>

在rails 5中效果很好。

答案 3 :(得分:0)

另一个选项(如果您需要添加数据属性或其他)

= content_tag(:select) do
  - for a in array
    option data-url=a.url selected=(a.value == true) a.name

答案 4 :(得分:0)

已经解释过,将尝试举例说明如何在没有options_for_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,则设置选中: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_list = [ 'eligible', 'ineligible' ]

现在所选的只需

<%= f.select :to_vote, select_list, selected: 'ineligible' %>