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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Arel lets you build column predicates programmatically and combine them with reduce(:or) and reduce(:and).
- 2sanitize_sql_like escapes user input so LIKE wildcards in a query can't break or hijack the SQL.
- 3An Arel CASE expression in ORDER BY gives you cheap relevance ranking without a dedicated search engine.
Related explainers
ruby
module Rack class MaintenanceMode RETRY_AFTER = 3600
A Rack maintenance-mode middleware in Rails
middleware
rack
http-status
Intermediate
8 steps
ruby
class ImageNormalizer ORIENTATION_TRANSFORMS = { 1 => ->(img) {}, 2 => ->(img) { img.flop },
Correcting EXIF orientation in Ruby
lookup-table
lambdas
image-processing
Intermediate
7 steps
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
ruby
class Spellchecker ALPHABET = ('a'..'z').to_a.freeze def initialize(dictionary)
Building a Norvig-style spellchecker in Ruby
edit-distance
levenshtein
dynamic-programming
Advanced
10 steps
ruby
class Order < ApplicationRecord belongs_to :customer has_many :line_items has_many :products, through: :line_items
How scopes compose in a Rails model
scopes
activerecord
subqueries
Intermediate
7 steps
ruby
require "charlock_holmes" class TextFileNormalizer DEFAULT_CONFIDENCE = 60
Normalizing text files to clean UTF-8 in Ruby
encoding
text-processing
file-io
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-multi-term-search-scope-in-rails-explained-ruby-205e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.