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
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 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.