Rails:使用select选项在多个模型中搜索

时间:2014-04-08 21:11:57

标签: ruby-on-rails solr full-text-search sunspot

我正在使用太阳黑子宝石并希望实现这样的搜索表单 enter image description here

我有两个模型文章和书籍

这是我的文章模型

class Article < ActiveRecord::Base

searchable do
  text :title
  text :content
end

这是我的书籍模型

class Book < ActiveRecord::Base

searchable do
  text :title
  text :description
end

我想知道如何实现这样的搜索表单,用户可以选择他们想要搜索书籍或文章的内容

2 个答案:

答案 0 :(得分:1)

试试这个

 http://railscasts.com/episodes/278-search-with-sunspot

的Gemfile

 gem 'sunspot_rails'

的bash

 bundle
 rails g sunspot_rails:install
 rake sunspot:solr:start
 rake sunspot:reindex

模型/ article.rb

 searchable do
   text :name, :boost => 5
   text :content, :publish_month
   text :comments do
     comments.map(&:content)
   end

   time :published_at
   string :publish_month
 end

  def publish_month
    published_at.strftime("%B %Y")
  end

articles_controller.rb

  def index
    @search = Article.search do
      fulltext params[:search]
      with(:published_at).less_than(Time.zone.now)
      facet(:publish_month)
      with(:publish_month, params[:month]) if params[:month].present?
    end
    @articles = @search.results
  end

物品/ index.html.erb

 <%= form_tag articles_path, :method => :get do %>
   <p>
     <%= text_field_tag :search, params[:search] %>
     <%= submit_tag "Search", :name => nil %>
   </p>
 <% end %>

 <div id="facets">
   <h3>Published</h3>
    <ul>
      <% for row in @search.facet(:publish_month).rows %>
      <li>
         <% if params[:month].blank? %>
           <%= link_to row.value, :month => row.value %> (<%= row.count %>)
         <% else %>
           <strong><%= row.value %></strong> (<%= link_to "remove", :month => nil %>)
         <% end %>
      </li>
      <% end %>
    </ul>
 </div>

答案 1 :(得分:1)

看看来自activerecord-hackery的ransack。 它提供了各种执行搜索的方法

https://github.com/activerecord-hackery/ransack

Rayan Bates为同一个录制了一段轨道广播。

http://railscasts.com/episodes/370-ransack