【问题标题】:How to allow a user to click on a search icon in order to run his search query using elasticsearch/searchkick?如何允许用户单击搜索图标以使用 elasticsearch/searchkick 运行他的搜索查询?
【发布时间】:2017-05-30 00:34:32
【问题描述】:

我能够使用 elasticsearch/searchkick 在导航栏上完美运行基本搜索字段。目前,执行查询的唯一方法是用户键入然后在他或她的键盘上按 Enter。但是,我还想允许用户输入他们的查询,然后单击搜索图标并执行搜索。如果有人可以帮助我,将不胜感激,我在下面列出了所有相关代码。

Book.rb

class Book < ApplicationRecord
has_many :likes, :counter_cache => true
has_many :users, through: :likes

searchkick
end

books_controller.rb

class BooksController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
before_action :set_book, only: [:show, :edit, :update, :destroy, :share]

def index
@books = Book.all
end

def search
query = params[:q].presence || "*"
@booksearches = Book.search(query)
end

private
  def set_book
  @book = Book.find(params[:id])
end

def book_params
  params.require(:book).permit(:title, :author, :avatar)
end

application_controller.rb

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def search
@booksearches = Book.search(params.fetch(:q, "*"))
end
end

application.html.erb

<body style="background-color: #f5f8fa; padding-top: 70px;" class="<%= @body_class %>">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li>
            <%= form_tag search_books_path, id:"searchform" do %>
                <%= text_field_tag :q, nil, placeholder: "Search..." %>
                <i class="fa fa-search" aria-hidden="true"></i>                     
            <% end %>
        </li>         
      </ul>
</div>
</nav>
</body>

【问题讨论】:

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


    【解决方案1】:

    经过更多研究,我意识到我缺少的是表单中的简单提交标签/提交类型。我在下面提供了对我有用的代码以及解释,以防其他人像我一样绊倒。

    步骤 1: 不包含提交标记或类型等于提交的按钮的表单将默认输入键作为提交操作。

    第 2 步(提交标签): 如果您使用带有文字且没有引导图标的提交按钮 - 只需添加提交标签即可解决问题。

    <%= submit_tag "Search", name: nill %>
    

    第 3 步:

    如果您使用引导图标 - 那么只需创建一个按钮并为其分配一种提交类型。

    <%= button_tag(type: "submit", class: "btn btn-default") do %>
    <i class="fa fa-search" aria-hidden="true"></i>
    <% end %>
    

    我的最终代码如下所示:

    <%= form_tag search_books_path,  id:"searchform" do %>
    <%= text_field_tag :q, nil, placeholder:"Search..." %>
    <%= button_tag(type: "submit", class: "btn btn-default") do %>
    <i class="fa fa-search" aria-hidden="true"></i>
    <% end %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2015-03-09
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多