Skip to content

Integration with Sunspot

Sam Pohlenz edited this page Oct 28, 2020 · 3 revisions

For heavy-duty search functionality, you may wish to run a Solr instance and integrate using the Sunspot gem.

Model

class Movie < ApplicationRecord
  searchable do
    # Full text search
    text :title
    text :director
    text :cast
    text :genre
    text :notes
    text :year

    # Sorting
    string :title_sort do
      ActiveSupport::Inflector.transliterate(title.downcase.sub(/^(an?|the)/, ''))
    end
    string :director_sort do
      ActiveSupport::Inflector.transliterate(director.to_s).downcase
    end
    string :cast_sort do
      ActiveSupport::Inflector.transliterate(cast.to_s).downcase
    end
    string :genre do
      genre.to_s.downcase
    end
    string :notes do
      notes.to_s.downcase
    end
    integer :year
  end
end

Admin

Trestle.resource(:sunspot, model: Movie) do
  adapter.include Trestle::Search::SunspotAdapter

  search do |query, params|
    Sunspot.new_search(model).build do
      fulltext(query) if query
      order_by(:title_sort, :asc) unless params[:sort]
    end
  end

  scope :year_1900_1949, label: "1900-1949" do |search|
    search.build { with(:year, 1900..1949) }
  end
  scope :year_1950_1999, label: "1950-1999" do |search|
    search.build { with(:year, 1950..1999) }
  end
  scope :year_2000_2050, label: "2000-2050" do |search|
    search.build { with(:year, 2000..2050) }
  end

  table do
    column(:title, link: true, sort: { field: :title_sort, default: true })
    column(:year)
    column(:director, sort: :director_sort)
    column(:cast, sort: :cast_sort)
    column(:genre)
    column(:notes)
  end
end
Clone this wiki locally