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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing user input with to_s.strip prevents nil errors and stray whitespace from reaching your query.
  2. 2sanitize_sql_like escapes LIKE wildcards so user input can't hijack pattern matching.
  3. 3Rendering a partial with explicit locals keeps the same markup usable across full pages and AJAX responses.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Live search suggestions in a Rails controller — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code