How to generate custom sorted query string URL in

2019-08-09 19:25发布

When I use link_to helper in Rails 3.0.7 app with many parameters, it generates a lexicographically sorted url as probably mentioned in the to_param method for Hash in Activesupport documentation. e.g.

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

generates

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

but what i want is

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

Anyone able to do custom sorting as supplied in the params hash to link_to or url_for ?

Unless I am missing something, this seems to contradict the example given in the documentation for link_to (either ri link_to or in 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 do manual URL creation like

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

but that would be missing the 'Rails way' and has some issue in Escaping certain chars, so would be the last option.

2条回答
淡お忘
2楼-- · 2019-08-09 19:48

Digging through the commit logs of rails, it appears that to_param sort is being re-introduce in rails 3.0.2 or so. Here is 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 monkey-patched the file by removing ".sort" and the order of query string is as desired. Could implementing a custom to_param be solution to getting a custom sort/no-sort query string? In that case, where should it be put?

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-09 19:49

A little late, but for someone else who comes across this post, using to_query can help. See here the old docs or the new docs

查看更多
登录 后发表回答