删除 form_tag 中 select_tag 的 include_blank 的空 URL 参数

Remove Empty URL Param for include_blank with select_tag in form_tag

当我提交一个表单来搜索和显示一些数据时,如果选择了 "include_blank" 值,我不希望 url 中出现一个空参数。

<%= form_tag(search_index_path, method: :get) do %>
  <%= select_tag(
        'fruit_selection',
        options_for_select(['Apple', 'Banana', 'Pear'], @prev_fruit_search),
        include_blank: 'All Fruit'
      ) %>
  <%= submit_tag('Search', name: nil) %>
<% end %>

我 expect/would 喜欢:

  1. 苹果:mysite.com?fruit_selection=苹果
  2. 香蕉:mysite.com?fruit_selection=香蕉
  3. 梨:mysite.com?fruit_selection=梨
  4. 所有水果:mysite.com

但是,我得到的是:

  1. 苹果:mysite.com?fruit_selection=苹果
  2. 香蕉:mysite.com?fruit_selection=香蕉
  3. 梨:mysite.com?fruit_selection=梨
  4. 所有水果:mysite.com?fruit_selection=

以下代码段允许 'All Fruit' 成为 default/first 选项。

When 'All Fruit' is selected, the url query parameter will appear as 'mysite.com?fruit_selection=All+Fruit' instead of the unaesthetic 'mysite.com?fruit_selection='.

当@prev_fruit_search 不为 nil 时,它的值将被选为选项,否则 'All Fruit' 将被选为选项。

<%= form_tag(search_index_path, method: :get) do %>
  <%= select_tag(
        'fruit_selection',
        options_for_select(
          ['All Fruit'] + ['Apple', 'Banana', 'Pear'],
          @prev_fruit_search || 'All Fruit'
        )
      ) %>
  <%= submit_tag('Search', name: nil) %>
<% end %>