Loenvpy
Loenvpy

Reputation: 919

Rails: search in multiple model with select option

I am using sunspot gem and want to implement a search form like this enter image description here

I have two model articles and books

this is my articles model

class Article < ActiveRecord::Base

searchable do
  text :title
  text :content
end

this my books model

class Book < ActiveRecord::Base

searchable do
  text :title
  text :description
end

i want to know how to implement the search form like this where user choose what they want to search books or articles

Upvotes: 2

Views: 833

Answers (2)

bsvin33t
bsvin33t

Reputation: 638

Take a look at ransack from activerecord-hackery. It provides various ways to perform searching

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

Rayan Bates has recorded an episode of railscasts for the same

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

Upvotes: 1

Carlos Morales
Carlos Morales

Reputation: 1149

try this

 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

models/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

articles/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>

Upvotes: 1

Related Questions