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

♀尐吖头ヾ 提交于 2019-12-24 08:25:42

问题


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.


回答1:


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?




回答2:


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



来源:https://stackoverflow.com/questions/6047402/how-to-generate-custom-sorted-query-string-url-in-rails-link-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!