如果没有找到搜索结果,请显示表格Sunspot Solr Rails 3

时间:2015-03-27 03:33:05

标签: ruby-on-rails ruby ruby-on-rails-3 solr sunspot

我正在使用Sunspot和Solr全文搜索我的rails应用程序。我想弄清楚如何在没有返回搜索结果时显示表单(或链接)。当没有找到任何内容时,它目前只显示我的空白索引页面。我会用if / else语句吗?

这是我的模型(dairy.rb)

class Dairy < ActiveRecord::Base
 attr_accessible :title

  searchable do
  text :title       
 end
end

和控制器(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

和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>

如果您需要任何其他页面,请告诉我。可能是一种非常简单的方式来做我想做的事,但我还在学习。我的真正目标是在找不到搜索结果时提供联系表单。谢谢!!

1 个答案:

答案 0 :(得分:0)

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 

或在视图中

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