sameetandpotatoes
sameetandpotatoes

Reputation: 1220

Rails4- Sunspot- fulltext params[:search] always returns no results

I am using Rails 4 and I am trying to use the Sunspot gem to implement a search engine for my website, but my search always returns no results. I have confirmed that the text I am searching is in fact in my :title or :text attributes in my Content model.

My Content.rb model:

class Content < ActiveRecord::Base
    searchable do
        string :title
        text :text
    end
    validates :title, presence: true
    validates :text, presence: true
    has_many :links
    validates_associated :links
    accepts_nested_attributes_for :links
end

My search form located in application.html.haml:

  = form_tag search_path, :method => :get do
%p
  = text_field_tag :search, params[:search]
  = submit_tag "Search"

My contents_controller.rb controller:

class ContentsController < ApplicationController
    ...
    def search
        if params[:search]
            @search = Content.search do
                fulltext params[:search]
            end
            @query = params[:search]
            @content = @search.results
        else
            @content = Content.all
        end
    end
    ...
end

My Gemfile:

  ...
  gem 'sunspot_rails'
  gem 'sunspot_solr'
  ...

My search.html.haml file that is called after def search in my Contents Controller:

-if @content.empty? || @query == nil
    %p="No results found for: #{@query}"
-elsif [email protected]?
    %p="Your search results for #{@query}"
[email protected] do |c|
    %h1.content-title=link_to removeHTML(c.title), content_path(c)
    %p.content-text=removeHTML(c.text.split[0..25].join(" ")) + " ..."

What's happening in the code above is that my @content is always empty. This occurs after the line @content = @search.results. I have verified this because if I remove the line and call @content = Content.all, it displays all of my Content objects, as expected.

Can anyone help me understand why @search.results returns nil?

Upvotes: 2

Views: 1591

Answers (1)

zrl3dx
zrl3dx

Reputation: 7869

Seems like you need to reindex data with:

rake sunspot:solr:reindex

You can fetch Content.all because you're doing it with bypassing solr, with query you're using search engine which returns always empty set because it doesn't have any indices.

Upvotes: 11

Related Questions