我有一个带搜索表单的Rails5索引,可以过滤结果。
所述表单使用remote: true命中控制器,更新结果并使用相应的index.js.erb文件更新结果容器。
我要解决的问题是,单击一个结果,然后向后导航,并不能保持以前的搜索。
我已经在index.js.erb中使用下面的代码修复了这个问题
// new fields to update the history
const url = new URL(window.location);
url.searchParams.set('query', '<%= params[:query] %>');
url.searchParams.set('query_sort', '<%= params[:query_sort] %>');
window.history.pushState(null, null, url);
// existing code to update the results
$('#container').replaceWith("<%= escape_javascript(render partial: 'partial') %>");然而,这感觉很复杂,好像应该有更好的(内置?)解决方案。
有谁知道实现这一目标的传统方法吗?如果没有,任何关于有效方法的想法都是非常感谢的。提前谢谢。
发布于 2019-10-25 19:33:17
您可以使用request.referrer获取当前浏览器的URL,并使用ruby对其进行操作。
使用ruby的完整代码应该是这样的:
index.js.erb
// new fields to update the history
<%
url = request.referrer
uri = URI.parse(url)
query = Rack::Utils.parse_query(uri.query)
query['query'] = params[:query]
query['query_sort'] = params[:query_sort]
uri.query = Rack::Utils.build_query(query)
%>
window.history.pushState(null, null, '<%= uri.to_s %>');
// existing code to update the results
$('#container').replaceWith("<%= escape_javascript(render partial: 'partial') %>");https://stackoverflow.com/questions/58556763
复制相似问题