select_tag和options_from_collection_for_select具有预先选择的值

时间:2018-05-15 17:22:45

标签: ruby-on-rails

我正在使用select_tag,我想要一个预选值,其中“0”为值,“All Events”为标签。这就是我的尝试:

<%= select_tag "Filter Event", options_from_collection_for_select(Event.all, :id, :name), include_blank: 'All Events', class: "pull-right", id: 'filter_event' %>

但渲染的html看起来像这样:

<select name="Filter Event" id="filter_event">
  <option value="">All Events</option>
  <option value="1">Event 1</option>
  <option value="2">Event 2</option>
</select> 

注意All Events的值是一个空字符串。我需要值“0”。什么是最好的方法?

1 个答案:

答案 0 :(得分:0)

不优雅,但有效:

<%= select_tag "Filter Event", options_for_select( Event.all.collect {|e| [e.name, e.id]  }.unshift(["All Events", 0]) ), id: 'filter_event', style: "position: relative; left: 200px; top: 43px" %>

options_from_collection_for_select需要一组响应所提供属性的对象。 options_for_select更灵活,因为它是一个数组元素数组。这允许您轻松修改阵列。