Rails select_tag in alphabetical order

I have this select_tag

 select_tag :id, options_for_select(Portal.all.collect{|p| [p.name, portal_datum_path(p.id)]}, [@portal.name, portal_datum_path(@portal)]), :onChange => "window.location=($(this).val());" 

It allows the user to select a portal where you can see certain elements that I want to display on these portals in alphabetical order.

I tried to arrange: the name in the controller, but did not win.

 def index @portals = Portal.with_name_or_subdomain(params[:keyword]).order(:name).limit(100) end 

I looked at the docs rails, there are no built-in options in the select_tag element itself, is there any secret parameter that I should use?

+4
source share
3 answers

after an hour, all you have to do is a .sort array of parameters that are passed to the_for_select option. it's my hack to fix it, but not very sexy

 select_tag :id, options_for_select(Portal.all.collect{|p| [p.name, portal_datum_path(p.id)]}.sort, [@portal.name, portal_datum_path(@portal)]), :onChange => "window.location=($(this).val());" 

hope that helps

+4
source

change it to

  select_tag: id, options_from_collection_for_select (portals,: name,: id, 1),: onChange => "window.location = ($ (this) .val ());" ** strong text **
+1
source

Collect your parameters into an array, as you did:

 options = Portal.all.collect{|p| [p.name, portal_datum_path(p.id)]}, [@portal.name, portal_datum_path(@portal)]) 

Then sort:

 options.sort!{ |x, y| x[0] <=> y[0] } 

I do this in the monkeys patch options_for_select, which is part of the module that I created to handle all kinds of selection material, since sort like this sorting is more common than not.

 def options_for_select(options, selected_items:nil, alphabetize: true) options.sort!{ |x, y| x[0] <=> y[0] } if alphabetize super(options, selected_items) end 
+1
source

All Articles