如何在Rails link_to中生成自定义排序查询字符串URL? [英] How to generate custom sorted query string URL in Rails link_to?
问题描述
当我在Rails 3.0.7应用程序中使用具有许多参数的link_to帮助器时,它会生成按字典顺序排序的url,这可能在Activesupport文档中的Hash的to_param方法中提到过.例如
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"}
产生
"/search?page=4&q=some+query&u=user"
但是我想要的是
"/search?u=user&q=some+query&page=4"
任何人都可以像params哈希中提供的那样对link_to或url_for进行自定义排序吗?
Anyone able to do custom sorting as supplied in the params hash to link_to or url_for ?
除非我丢失了某些内容,否则这似乎与文档中link_to(ri link_to
或文件/gems/actionpack-3.0.7/lib/action_view/helpers/url_helper.rb:215
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&baz=quux">Nonsense search</a>
当然,我可以像
link_to "my Link", "/search?u=#{user}&q=#{query}&page=#{page}"
但是这将丢失"Rails方式",并且在转义某些字符方面存在一些问题,因此最后一种选择.
but that would be missing the 'Rails way' and has some issue in Escaping certain chars, so would be the last option.
推荐答案
在rails的提交日志中,似乎在<3> 0.2左右的版本中重新引入了 to_param sort .这是日志:
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
...
我通过删除".sort
"对文件进行了猴子修补,查询字符串的顺序是所需的.能否实现自定义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?
这篇关于如何在Rails link_to中生成自定义排序查询字符串URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!