在Rails中,如何防止我的搜索功能在页面加载时自动运行空白搜索?

时间:2019-04-28 23:03:49

标签: ruby-on-rails ruby

我有一个具有搜索功能的控制器。搜索功能会显示一条警告消息,提示用户用户未在搜索字段中输入任何内容。问题是页面加载时显示此消息-单击提交之前。我该如何预防?

这是我的控制器代码:

class LocationsController < ApplicationController
  before_action :authenticate_user!

  def index
    if params[:q].blank?
      @message = 'Please enter an address in the field!'
      return
    end

    token = Rails.application.credentials.locationiq_key
    search = LocationiqApi.new(token).find_place(params[:q])

    # Hash#dig will return nil if ANY part of the lookup fails
    latitude = search.dig('searchresults', 'place', 'lat')
    longitude = search.dig('searchresults', 'place', 'lon')

    if latitude.nil? || longitude.nil?
      # Output an error message if lat or lon is nil
      @coordinates = "We couldn't find a place by this name. Please enter a valid place name."
    else
      @coordinates = "Coordinates: " + "#{latitude}, #{longitude}"
    end
  end
end

和我的观点:

<main>
  <h1>Location Search</h1>
  <!-- devise flash messages -->
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  <!-- Button to search coordinates -->
  <%= form_tag(locations_path, method: :get) do %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("geocode") %>
    <%= @message %>
  <% end %><br>

  <%= @coordinates %>
</main>

1 个答案:

答案 0 :(得分:0)

添加内部位置搜索表单,

<%= hidden_field_tag 'location_search', true %>

在控制器中检查为

if  params[:location_search] && params[:q].blank?
   @message = 'Please enter an address in the field!'
   return
end