简体   繁体   English

Rails - 导航返回时使用远程表单维护参数(搜索历史)

[英]Rails - maintain params (search history) with remote form when navigating back

I've a Rails 5 index with a search form that filters the results.我有一个带有过滤结果的搜索表单的 Rails 5 索引。

Said form uses remote: true to hit the controller, update the results the uses the relevant index.js.erb file to update the results container.上述表格使用remote: true打controller,更新结果使用相关的index.js.erb文件更新结果容器。

The issue I'm addressing is that clicking a result followed by navigating back doesn't maintain the previous search.我要解决的问题是单击结果然后返回并不会保留以前的搜索。

I've fixed this using the following in 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') %>");

However, this feels convoluted and like there should be a better (inbuilt?) solution.然而,这感觉很复杂,应该有更好的(内置的?)解决方案。

Does anyone know of the conventional way of achieving this?有谁知道实现这一目标的传统方法? If not, any ideas on an efficient approach are much appreciated.如果没有,任何关于有效方法的想法都非常感谢。 Thanks in advance.提前致谢。

You can use request.referrer to get the current browser URL and manipulate this using ruby.您可以使用request.referrer获取当前浏览器 URL 并使用 ruby 进行操作。

Full code using ruby should be something like this:使用 ruby 的完整代码应该是这样的:

index.js.erb 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') %>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM