How to create your own sorted query string URL in Rails link_to?

When I use link_to helper in a Rails 3.0.7 application with many parameters, it generates a lexicographically sorted URL, as is probably mentioned in the to_param method for the Hash in Activesupport documentation. eg.

link_to "my Link", {:u=>"user", :q=>"some query", :page=>"4"} 

generates

 "/search?page=4&q=some+query&u=user" 

but I want

 "/search?u=user&q=some+query&page=4" 

Anyone who can do the custom sort specified in the hash options to link_to or url_for?

If something is missing for me, it seems to contradict the example given in the documentation for link_to (either ri link_to , or in the file /gems/actionpack-3.0.7/lib/action_view/helpers/url_helper.rb:215

  # link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux") # # => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a> 

Of course, I can create a manual URL creation like

 link_to "my Link", "/search?u=#{user}&q=#{query}&page=#{page}" 

but this will be missing the โ€œRails pathโ€ and has some problems when escaping certain characters, so this will be the last option.

+1
source share
2 answers

Delving into rail fixing logs, it seems that the to_param sort is re-introduced in rails 3.0.2 or so. Here is the log:

  $ git log activesupport/lib/active_support/core_ext/object/to_param.rb ... commit 10dec0e65e1f4d87f411b4361045eba86b121be9 Author: Xavier Noria < fxn@hashref.com > Date: Tue Sep 28 00:32:20 2010 +0200 let Hash#to_param and Hash#to_query sort again This was a regression introduced in 5c858220085dc4ddc1bec496747059dfbe32f1da. We bring sorting back because people rely on it, eg for constructing consistent cache keys. commit 5c858220085dc4ddc1bec496747059dfbe32f1da Author: Santiago Pastorino < santiago@wyeworks.com > Date: Thu Jul 22 05:08:34 2010 +0800 Hash#to_param is doesn't use sort anymore, some tests added for Hash#to_param ... 

I decapitated the file by deleting " .sort ", and the query line order is optional. Could a custom to_param implementation be a solution to get a custom sort request string / without sorting? In this case, where should it be put?

+1
source

A bit late, but for someone who comes across this post, to_query help may help. See here old documents or new documents

0
source

All Articles