Rails:在 link_to 中保留 GET 查询字符串参数
我的应用程序中有一个典型的搜索工具,它返回一个结果列表,可以对这些结果进行分页、排序、使用不同的records_per_page值进行查看等。每个选项都由查询字符串中的参数控制。一个简化的示例:
/search?q=test&page=2
现在假设我需要显示一组将records_per_page 值设置为10、20、30 的链接。每个链接必须包含现有的查询参数(可以是一个很长的集合)以及一个新的per_page 参数。
/search?q=test&page=2& ... &per_page=10
/search?q=test&page=2& ... &per_page=20
/search?q=test&page=2& ... &per_page=30
有没有一种简单的方法可以仅使用 link_to helper 来完成此操作,或者我需要以某种方式解析并重现以前请求中的查询字符串?
I have a typical search facility in my app which returns a list of results that can be paginated, sorted, viewed with a different records_per_page value, etc. Each of these options is controlled by parameters in the query string. A simplified example:
/search?q=test&page=2
Now say I need to display a set of links that set records_per_page value to 10, 20, 30. Each link must include the existing query parameters, which can be a very long set, plus a new per_page parameter.
/search?q=test&page=2& ... &per_page=10
/search?q=test&page=2& ... &per_page=20
/search?q=test&page=2& ... &per_page=30
Is there an easy way to do it with just link_to helper or I need to parse and reproduce the query string from previous request somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
将新参数与查询参数合并而不是与所有参数(包括通过路径获取的参数)合并的最简单方法是与 request.query_parameters 合并
,否则最终会得到重复路径参数的查询字符串,例如
?action=index&controller=products&foo=bar
而不是?foo=bar
。The simplest way to merge the new params with the query parameters and NOT with all parameters (including those obtained through the path) is to merge with request.query_parameters
Otherwise you end up with query strings duplicating the path parameters, for example
?action=index&controller=products&foo=bar
instead of?foo=bar
.如果您想保留现有参数并且不让自己遭受 XSS 攻击,请务必清理参数哈希,仅保留您的应用程序可以发送的参数
:
如果您在多个地方使用它,请清理控制器中的参数:
If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:
If you use it in multiple places, clean the params in the controller:
您只需将
params
哈希值的元素抛出到link_to
即可。喜欢You can just throw elements of the
params
hash atlink_to
. Like如果您正在处理的链接不是通过 request.params 提供给您的,则此方法有效。
This works if the links you are processing aren't given to you by request.params.
又怎样呢
?
What about
?
我知道有点晚了..
如果您使用它作为过滤搜索结果的方式,请查看我的助手:)
这会自动删除所有空白和不需要的参数,并添加“selected”类(如果所有新参数都已设置) 。
然后您可以在您的视图中使用它:
或者在您的情况下:
A bit late i know..
If your using this as a way to filter search results have a look at my helper :)
This automagicly removes all blank and unneeded params and add the class "selected" if all of it's new params were already set.
You can then just use this in your view:
Or in your case: