Ruby-on-rails, select_tag and options_from_collection_for_select with selected item after reload page

StackOverflow https://stackoverflow.com/questions/21326395

문제

I do not show my selected data in select_tag with options_from_collection_for_select with option :onchange.

I have this form

<%= 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 %>

I select 'Aircompanies'('search_al'). The page reload because I have option in select_tag :onchange, but selected data do not show in selected data. 'All Airlines' show in Select_tag again.

How can I display my data in Select_tag?

도움이 되었습니까?

해결책

The method options_from_collection_for_select accepts an optional selected argument, which marks that <option> as selected. Update your code as follows:

<%= 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 %>

See the API for additional information: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_from_collection_for_select


A few other nitpicks and advice:

Choose a syntax, and use it every time, at least in the same file/method/block/etc. Why? Looks cleaner... Example:

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

Use virtual attributes as much as possible from the controller.Why? Looks cleaner AND if you decide to change how you retrieve @airlines, it's easier to do it in the controllers then tracking it down in the views. Example:

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

Personal preference, I try to never use onchange, instead I separate view and js using event-listeners. Why? Looks cleaner and I'm able to re-use the same js across the app WHILE only having to change it in one place.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top