ruby
20 lines · 6 steps
Live search suggestions in a Rails controller
A controller action safely queries products by name or SKU and renders a reusable partial.
Explained by
highlit
1class SearchController < ApplicationController
2 def index
3 @query = params[:q].to_s.strip
4 end
5
6 def suggestions
7 @query = params[:q].to_s.strip
8
9 if @query.length < 2
10 @products = Product.none
11 else
12 @products = Product
13 .where("name ILIKE :q OR sku ILIKE :q", q: "%#{Product.sanitize_sql_like(@query)}%")
14 .order(popularity: :desc)
15 .limit(8)
16 end
17
18 render partial: "search/suggestions", locals: { products: @products, query: @query }
19 end
20end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing user input with to_s.strip prevents nil errors and stray whitespace from reaching your query.
- 2sanitize_sql_like escapes LIKE wildcards so user input can't hijack pattern matching.
- 3Rendering a partial with explicit locals keeps the same markup usable across full pages and AJAX responses.
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
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 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/live-search-suggestions-in-a-rails-controller-explained-ruby-3db0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.