Rails - 在重定向上将变量传递给不同的页面

时间:2017-05-24 06:30:03

标签: ruby-on-rails ruby pg-search

感谢您的帮助。我将pg_search添加到我的项目中,如果根本没有搜索结果,则需要重定向用户。这是我的搜索控制器。

/app/controllers/results_controller.rb

class ResultsController < FrontendController
  def index
    @search_results = PgSearch.multisearch(params[:query])
    if @search_results.empty?
      redirect_to :back(@search_results)
    end
  end
end

这是我的布局,我试图抓住搜索结果:

/app/views/layouts/application.html.slim
...
    .search-result class="#{'visible' unless @search_results?}
      ' 0 results
...

我得到的只是

/app/views/layouts/application.html.slim:165: syntax error, unexpected ')' ...isible' unless@search_results?))).to_s)); _temple_html_attri... ... ^ 
/app/views/layouts/application.html.slim:168: syntax error, unexpected keyword_do_cond, expecting ')' ...method: :get, role: 'search' do; ... ^ 
/app/views/layouts/application.html.slim:171: syntax error, unexpected keyword_end, expecting ')' ; end; @output_buffer.safe_concat(... ^ /app/views/layouts/application.html.slim:194: syntax error, unexpected keyword_ensure, expecting ')' 
/app/views/layouts/application.html.slim:196: syntax error, unexpected keyword_end, expecting ')'

我从Stackoverflow获得了几种不同的方法,但没有任何帮助。我究竟做错了什么? Rails 4.2.5.1,Ruby 2.2.3

1 个答案:

答案 0 :(得分:3)

不要重定向。而是呈现一个视图,告诉用户没有搜索结果。否则,当你按下后退按钮时,你会得到无限循环。

class ResultsController < FrontendController
  def index
    @search_results = PgSearch.multisearch(params[:query])
  end
end
# app/views/results/index.html
<% if @search_results.any? do %>
  <% @search_results.each do |r| %>

  <% end %>
<% else %>
  No results.
  <%= render 'some_kind_of_form' %>
<% end >

为什么语法错误?

redirect_to :back :back中是一个文字符号。你不能在Ruby中调用文字:

irb(main):001:0> :foo("bar")
SyntaxError: (irb):1: syntax error, unexpected '(', expecting end-of-input
:foo("bar")

如果您想使用与url_for(:back)相同的网址request.referrer进行扩充。

# see https://ruby-doc.org/stdlib-2.1.2/libdoc/uri/rdoc/URI/HTTP.html
uri = URI(url_for(:back))
uri.query = { foo: 'bar' }.to_query
redirect_to uri

如果你想获得路线对象,你可以这样做:

Rails.application.routes.recognize_path(url_for(:back), method: :get)