Module: ConcernsOnRails::Models::Searchable

Extended by:
ActiveSupport::Concern
Defined in:
lib/concerns_on_rails/models/searchable.rb

Overview

LIKE-based search across one or more columns.

class Article < ApplicationRecord
include ConcernsOnRails::Searchable

searchable_by :title, :body                                  # defaults below
searchable_by :title, :body, mode: :all                      # every term must match
searchable_by :sku,         match: :prefix                   # "abc" -> "abc%"
searchable_by :code,        match: :exact, case_sensitive: true
end

Article.search("hello")            # WHERE title ILIKE '%hello%' OR body ILIKE '%hello%'
Article.search("")                 # no-op — returns the full relation
Article.search("foo").where(...)   # chainable like any scope

Options (all optional; the defaults reproduce a single-term, case-insensitive "contains" search across the given columns):

mode:           :any (default) treats the whole query as one term;
              :all splits on whitespace and requires every term to match.
match:          :contains (default, "%q%"), :prefix ("q%"), or :exact ("q").
case_sensitive: false (default) emits ILIKE on Postgres; true emits LIKE.
              NOTE: this only affects Postgres. On MySQL/SQLite, LIKE
              case sensitivity is governed by the column collation, so
              the flag is effectively a no-op there.

Uses Arel's matches. The query is escaped before interpolation, so % / _ / \ from user input are treated as literals.

Constant Summary collapse

LIKE_ESCAPE =
"\\".freeze
LIKE_SPECIAL =
/[\\%_]/
VALID_MODES =
%i[any all].freeze
VALID_MATCHES =
%i[contains prefix exact].freeze