2023-06-01 - Search


main topics


Gemfile

gem 'pg_search'

Then bundle install.

app/models/car.rb:

class Car < ApplicationRecord
  include PgSearch::Model
  pg_search_scope(
    :search_by_brand_model, # <- method name
    against: %i[brand model],
    using: { tsearch: { prefix: true } }
  )
  # ...
end

app/controllers/cars_controller.rb

def index
  if params[:query].present?
    @cars = Car.search_by_brand_model
  else
    @cars = Car.all
  end
end

app/views/shared/_navbar.html.erb (omitting html/erb tags and CSS classes):

form_with url: cars_path, method: :get, do
  text_field_tag :query, params[:query]
  submit_tag "Search", name: ""
end

Question: Why not use simple_form_for?

Answer: because the main benefit in using simple_form_for is when we give a model to it, so it can automagically understand what kind of data we want with f.input.