如何仅在用户按下搜索键时显示搜索结果

时间:2019-06-01 17:17:50

标签: ruby-on-rails ruby ruby-on-rails-5

有没有人知道如何仅在单击搜索按钮后才显示搜索结果?

此刻,我的页面当前正在显示@ flights.each中的所有内容。但我只希望这些信息在他们单击搜索后才可见:)

我的index.html.erb

<h1>Flights#index</h1>
<p>Find me in app/views/flights/index.html.erb</p>





From Airport:
<%= form_for(flights_index_path, method: :get) do %>
    <%= text_field_tag :from_airport_id, params[:from_airport_id] %>

    <%= submit_tag 'Search' %>
<% end %>

<% @flights.each do |f| %>
<br>
<br>

    Flight from <%= f.from_airport_id %>
    Arriving at <%= f.to_airport_id %>
<% end %>

我的控制器

class FlightsController < ApplicationController
  def index

    if params[:from_airport_id]
      @flights = Flight.where('from_airport_id LIKE ?', "%#{params[:from_airport_id]}%")
    else
      @flights = Flight.all
    end
  end


  private
    def flights_path
      params.require(:flight).permit(:flight, :from_airport_id)
    end

end

1 个答案:

答案 0 :(得分:2)

我相信这是因为您的@flights = Flight.all处于else状态。当没有查询时(例如,单击“提交”按钮并传递参数之后),它将默认显示所有排期。我会把这条线拿出来,只有

def index

    if params[:from_airport_id]
      @flights = Flight.where('from_airport_id LIKE ?', "%#{params[:from_airport_id]}%")
    else
      @flights = []
    end
  end

或者您可以在航班搜索中查找AJAX请求,并以这种方式呈现表格。