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
class ProjectsController < ApplicationController before_action :set_project, only: %i[show update destroy] def create
Scoping a Rails API controller to Current.account
multitenancy
strong-parameters
nested-attributes
Intermediate
7 steps
java
public List<User> findUsersByEmailDomain(String domain, int minAge) { String sql = """ SELECT id, username, email, age, created_at FROM users
Safe parameterized JDBC queries in Java
jdbc
sql-injection
prepared-statement
Intermediate
7 steps
ruby
class TasksController < ApplicationController before_action :set_project def reorder
Bulk task reordering with upsert_all in Rails
bulk-update
upsert
authorization
Intermediate
8 steps
ruby
require "openssl" require "json" require "base64"
Building signed session tokens in Ruby
hmac
authentication
cryptography
Intermediate
8 steps
ruby
class Product < ApplicationRecord belongs_to :category, touch: true has_many :reviews, dependent: :destroy
How Rails models wire up associations
active record
associations
validations
Intermediate
7 steps
typescript
import sanitizeHtml from "sanitize-html"; interface RichTextOptions { allowImages?: boolean;
Building a configurable HTML sanitizer allowlist
sanitization
xss-prevention
allowlist
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.