ruby 36 lines · 7 steps

Building a multi-term search scope in Rails

Two composable scopes turn a free-text query into safe Arel conditions and a relevance-ordered result set.

Explained by highlit
1class Product < ApplicationRecord
2 scope :search, ->(query) {
3 return all if query.blank?
4 
5 terms = query.to_s.strip.split(/\s+/)
6 searchable = arel_table
7 columns = [searchable[:name], searchable[:sku], searchable[:description], searchable[:brand]]
8 
9 conditions = terms.map do |term|
10 pattern = "%#{sanitize_sql_like(term)}%"
11 columns
12 .map { |column| column.matches(pattern) }
13 .reduce(:or)
14 end
15 
16 where(conditions.reduce(:and)).distinct
17 }
18 
19 scope :search_ranked, ->(query) {
20 relation = search(query)
21 return relation if query.blank?
22 
23 exact = "#{sanitize_sql_like(query.to_s.strip)}"
24 starts_with = arel_table[:name].matches("#{exact}%")
25 contains = arel_table[:name].matches("%#{exact}%")
26 
27 relation.order(
28 Arel::Nodes::Case.new
29 .when(arel_table[:name].eq(query)).then(0)
30 .when(starts_with).then(1)
31 .when(contains).then(2)
32 .else(3),
33 name: :asc
34 )
35 }
36end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Arel lets you build column predicates programmatically and combine them with reduce(:or) and reduce(:and).
  2. 2sanitize_sql_like escapes user input so LIKE wildcards in a query can't break or hijack the SQL.
  3. 3An Arel CASE expression in ORDER BY gives you cheap relevance ranking without a dedicated search engine.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a multi-term search scope in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code