Search code examples
ruby-on-railsrubyruby-on-rails-3solrsunspot

Show a form if no search results found Sunspot Solr Rails 3


I am using Sunspot and Solr to full text search my rails app. I am trying to figure out how to show a form (or a link) when no search results are returned. It currently will just show my blank index page when nothing is found. Would I do this with an if/else statement?

Here is my model (dairy.rb)

class Dairy < ActiveRecord::Base
 attr_accessible :title

  searchable do
  text :title       
 end
end

and controller (dairies_controller.rb)

class DairiesController < ApplicationController
 before_filter :set_dairy, only: [:show, :edit, :update, :destroy]

 respond_to :html

 def index
  @search = Sunspot.search [Dairy, Drink] do
  fulltext params[:search]
 end
  @results = @search.results
 end  

def show
 respond_with(@dairy)
end

def new
 @dairy = Dairy.new
 respond_with(@dairy)
end

def edit
end

def create
 @dairy = Dairy.new(params[:dairy])
 @dairy.save
 respond_with(@dairy)
end

def update
 @dairy.update_attributes(params[:dairy])
 respond_with(@dairy)
end

def destroy
 @dairy.destroy
 respond_with(@dairy)
end

private
 def set_dairy
 @dairy = Dairy.find(params[:id])
end
end

and index (index.html.erb)

<body class="DI">
 <%= form_tag dairies_path, :method => :get do %>
  <p>
    <%= text_field_tag :search, params[:search], style:"width:550px;     height:30px;", :autofocus => true %><br>
    <%= submit_tag "Search!", :name => nil, class: "btn btn-primary btn-lg", style: "margin-top:10px" %>
  </p>
<% end %>

<%= link_to 'Add New Item', new_dairy_path, class: "btn btn-default" %>
<p id="notice"><%= notice %></p>

<table>
 <thead>
  <tr>
    <th>Title</th>
    <th colspan="3"></th>
  </tr>
</thead>

<tbody>
  <% @results.each do |dairy| %>
    <tr>
      <td><%= dairy.title %></td>
      <td><%= link_to 'Show', dairy %></td>
      <td><%= link_to 'Edit', edit_dairy_path(dairy) %></td>
      <td><%= link_to 'Destroy', dairy, method: :delete, data: { confirm:  'Are you sure?' } %></td>
    </tr>
   <% end %>
  </tbody>
 </table>
</body>

Let me know if you need any other pages. Probably a very simply way to do what I want, but I am still learning. My real goal is to have a contact form when no search results are found. Thank you!!


Solution

  • def index
      @search = Sunspot.search [Dairy, Drink] do
        fulltext params[:search]
      end
      if @search.results.any?
        @results = @search.results
      else
        return redirect_to some_path
      end
    end 
    

    or in the view

    if @results.any?
      render partial: 'list_results'
    else
      render partial: 'empty_results'
    end