【发布时间】:2013-08-16 15:21:38
【问题描述】:
我正在使用 Rails 4,并尝试使用 Sunspot gem 为我的网站实现搜索引擎,但我的搜索始终没有返回任何结果。我已确认我正在搜索的文本实际上在我的内容模型中的 :title 或 :text 属性中。
我的Content.rb 模特:
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
我的搜索表单位于application.html.haml:
= form_tag search_path, :method => :get do
%p
= text_field_tag :search, params[:search]
= submit_tag "Search"
我的contents_controller.rb 控制器:
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
我的Gemfile:
...
gem 'sunspot_rails'
gem 'sunspot_solr'
...
我的search.html.haml 文件在我的Contents Controller 中的def search 之后调用:
-if @content.empty? || @query == nil
%p="No results found for: #{@query}"
-elsif !@query.empty?
%p="Your search results for #{@query}"
-@content.each do |c|
%h1.content-title=link_to removeHTML(c.title), content_path(c)
%p.content-text=removeHTML(c.text.split[0..25].join(" ")) + " ..."
上面代码中发生的事情是我的@content总是为空。这发生在@content = @search.results 行之后。我已经验证了这一点,因为如果我删除该行并调用 @content = Content.all,它会按预期显示我的所有内容对象。
谁能帮我理解为什么@search.results返回nil?
【问题讨论】:
标签: ruby-on-rails search ruby-on-rails-4 sunspot