重载页面后,Ruby-on-rails,select_tag和options_from_collection_for_select以及所选项目

时间:2014-01-24 06:59:21

标签: ruby-on-rails onchange html-select

我没有在select_tag中显示我选择的数据,其中options_from_collection_for_select带有选项:onchange。

我有这个表格

<%= form_tag "/airports/#{@airport.id}/board_out/", :method => 'get', :id => "timetableaps_search", :prompt => "" do %>
  <%= @selected  = params[:search]%>
  <%= select_tag "search_al", options_from_collection_for_select(@t.map(&:aircompany).uniq.sort_by(&:airline_name), :id, :airline_name), :selected => params[:search_al], prompt: "All Airlines", :onchange => "this.form.submit();"%>
  <%= select_tag "search_ap", options_from_collection_for_select(@t.group("apname").order("cityname"),"way_end", "apname"), prompt: "All Airports", :onchange => "this.form.submit();" %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

我选择'Aircompanies'('search_al')。页面重新加载,因为我在select_tag:onchange中有选项,但所选数据不显示在所选数据中。 “所有航空公司”再次在Select_tag中显示。

如何在Select_tag中显示我的数据?

1 个答案:

答案 0 :(得分:1)

方法options_from_collection_for_select接受一个可选的selected参数,该参数将<option>标记为已选中。更新您的代码如下:

<%= form_tag "/airports/#{@airport.id}/tablo_out/", :method => 'get', :id => "timetableaps_sear$
  <%= @selected = params[:search]%>
  <%= select_tag "search_al", options_from_collection_for_select(@t.map(&:aircompany).uniq.sort_by(&:airline_name), :id, :airline_name, params[:search_al]), prompt: "All Airlines", onchange: "this.form.submit();"%>
  <%= select_tag "search", options_from_collection_for_select(@t.group("apname").order("cityname"),"way_end", "apname", @selected), prompt: "All Airports", onchange: "this.form.submit();" %>
  <%= submit_tag "Search", name: nil %>
<% end %>

有关其他信息,请参阅API: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_from_collection_for_select


其他一些挑剔和建议:

选择语法,每次都使用它,至少在同一个文件/方法/块/等中使用。为什么?看起来更干净......例如:

:this => "that" vs this: "that"

尽可能从控制器中使用虚拟属性。为什么?看起来更干净如果你决定改变检索@airlines的方式,那么在控制器中更容易,然后在视图中跟踪它。例如:

@t.map(&:aircompany).uniq.sort_by(&:airline_name) vs @airlines

个人偏好,我尝试永远不会使用onchange,而是使用事件监听器分隔视图和js。为什么?看起来更干净,我可以在应用程序中重复使用相同的js,只需在一个地方更改它。