-
Notifications
You must be signed in to change notification settings - Fork 11
Integration with ActiveRecord (ILIKE)
Sam Pohlenz edited this page Oct 28, 2020
·
3 revisions
For the most basic search functionality, you can use PostgreSQL's built-in ILIKE function within a where
clause. This type of search uses ActiveRecord only and does not require any additional gems.
class Movie < ApplicationRecord
scope :between, ->(from, to) { where("year >= :from AND year <= :to", from: from, to: to) }
end
Trestle.resource(:movies) do
collection do
Movie.order(title: :asc)
end
search do |query|
query ? collection.where("title ILIKE ?", "%#{query}%") : collection
end
scope :all, default: true
scope :year_1900_1949, -> { Movie.between(1900, 1949) }, label: "1900-1949"
scope :year_1950_1999, -> { Movie.between(1950, 1999) }, label: "1950-1999"
scope :year_2000_2049, -> { Movie.between(2000, 2049) }, label: "2000-2049"
end
Adding a trgm index will speed up searches.
class AddTitleTrgmIndex < ActiveRecord::Migration[5.1]
disable_ddl_transaction!
def change
enable_extension :pg_trgm
reversible do |dir|
dir.up { execute("CREATE INDEX CONCURRENTLY movies_title_idx ON movies USING gin(title gin_trgm_ops)") }
dir.down { execute("DROP INDEX movies_title_idx") }
end
end
end
See https://about.gitlab.com/2016/03/18/fast-search-using-postgresql-trigram-indexes/ for more information on this type of index.