当我在Rails 3.0.7应用程序中使用带有许多参数的link_to helper时,它会生成一个按字典顺序排序的URL,可能在ActiveSupport文档中的Hash的to_param方法中提到。 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 hash中提供自定义排序到link_to或url_for吗?
除非我遗漏了某些内容,否则这似乎与link_to(ri link_to
或文件/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>
当然,我可以像
那样进行手动创建URLlink_to "my Link", "/search?u=#{user}&q=#{query}&page=#{page}"
但是这会错过'Rails方式'并且在转义某些字符时会遇到一些问题,所以这将是最后一个选项。
答案 0 :(得分:1)
挖掘rails的提交日志,似乎 to_param sort 正在rails 3.0.2中重新引入。这是日志:
$ 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是否可以获得自定义排序/无排序查询字符串?在那种情况下,它应该放在哪里?