Search code examples
ruby-on-railssearchsunspot

Text search not working with sunspot rails


I'm currently implementing a basic search bar with sunspot. My code seems to work but the search result always returns no object. I don't understand why and after reading all the sunspot documentation, I'm a bit lost. If anyone can just give me a clue, it could be very helpful. Here is my code :

My controller:

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy]
  respond_to :html

  def index
    @search = Book.search do
      fulltext(params[:search])
    end
    @books = @search.results  
   respond_with(@books)
  end
# ADDITIONAL CODE
end

My model:

class Book < ActiveRecord::Base
  has_many :wishs
  has_many :loans

  validates_presence_of :title, :author, :description

  enum status: [ :available, :unavailable, :on_loan ]

  searchable do
    string :title
    string :author
    string :description
  end
end

My view:

<div class="container">
  <div class="row">
    <h1>Listing books</h1>

    <%= form_tag books_path, :method => :get do %>
        <div class="input-group">
            <span class="input-group-btn">
              <%= submit_tag "Search", :name => nil, class: "btn btn-default" %>
            </span>
          <%= text_field_tag :search, params[:search], class: "form-control", placeholder: "Title, description, author ..." %>
        </div>
    <% end %>

    <table class="table table-hover" style="margin-top: 20px">
      <thead>
      <tr>
        <!-- NAME OF COLUMN -->
      </tr>
      </thead>

      <tbody>
      <% @books.each do |book| %>
        <!-- DO SOME STUFF -->
      <% end %>
      </tbody>
    </table>
  </div>
</div>

Solution

  • Instead of string use text so it will be a full-text search. In your model try:

    searchable do
      text :title
      text :author
      text :description
    end
    

    If that syntax fails, this will work

    searchable do
      text :title, :author, :description
    end
    

    In the end, a reindex looks to have fixed it: bundle exec rake sunspot:solr:reindex