簡體   English   中英

如果未找到搜索結果,則顯示表單Sunspot Solr Rails 3

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

我正在使用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.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>

讓我知道您是否需要其他頁面。 可能是做我想要的事情的一種非常簡單的方法,但我仍在學習。 我的真正目標是在找不到搜索結果時擁有聯系表。 謝謝!!

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  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM