开发者

How to generate custom sorted query string URL in Rails link_to?

开发者 https://www.devze.com 2023-03-06 15:39 出处:网络
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

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, s开发者_开发百科o would be the last option.


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消