FirstDEV blog
  • Home
  • Ruby
  • Ruby On Rails
  • Tips
  • Solutions
  • About
Subscribe

Rails-code

A collection of 19 posts

Rails-code

Add A Virtual Attribute To A Rails Model Without A Database Column

A signup form collects a full name that gets split into first and last. A settings form takes a confirmation checkbox that’s never stored. These need to behave like attributes — assignable, validatable,

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Scope Every Query To The Current User Without Polluting Every Method

Writing current_user.orders.find(params[:id]) everywhere works right up until someone writes Order.find(params[:id]) in a new controller and exposes another user’s data. The fix is to make the scoped path the only path.

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Cache An Expensive Scope In Rails With Automatic Cache Busting On Update

A dashboard query that aggregates across three tables takes 800ms and the underlying data changes a few times an hour. Caching it is obvious; the hard part is invalidating it without a scheduled

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Eager Load A Rails Association Only When It Exists To Avoid N1

includes(:profile) on a has_one loads a row per record even when most records have no profile. Filtering to the records that actually have the association, or loading it conditionally, keeps the query cheap

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Validate Uniqueness Of A Combination Of Two Columns In Rails

A user can only be a member of an organisation once. A product can only have one price per currency. The rule is not “this column is unique” but “this pair is unique”,

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Run Raw Sql In Rails And Map The Results To A Ruby Struct

Reporting queries with window functions, CTEs, and cross-table aggregates are painful to express in ActiveRecord and produce untyped hashes when you drop to SQL. Mapping the rows into a Struct gives you named

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Batch Process A Large Activerecord Query Without Memory Bloat

Order.all.each loads every row into memory before iterating. At forty thousand rows that is slow; at four million it is an out-of-memory kill. Rails has three batching methods and they solve slightly different

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Return Clean Consistent Json Errors From A Rails Api Controller

An API that returns a validation error one shape, a 404 another shape, and an HTML error page for anything unhandled forces every client to write three parsers. One rescue block in the

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Generate A Signed Expiring Url For An Active Storage Attachment

Private files — invoices, contracts, medical records — should not be served from a permanent public URL. Active Storage generates signed URLs that expire, so a leaked link stops working.

Rajan Bhattarai Rajan Bhattarai 1 min read
Rails-code

Upsert A Record In Rails Using Upsert_all With Conflict Resolution

Syncing from an external system means “create it if it is new, update it if it exists” for thousands of rows. Doing that with find_or_initialize_by in a loop is two queries per record;

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Find Records Where A Jsonb Column Contains A Specific Key In Rails

Settings bags, API payloads, and feature-flag hashes all end up in a jsonb column, and eventually you need to query them — every account with a particular preference set, every webhook whose payload

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Soft Delete Records In Rails Without A Gem Using Discarded_at

Some records should disappear from the application without leaving the database — orders referenced by invoices, users referenced by audit logs. A nullable timestamp column and a default scope gives you soft deletion

Rajan Bhattarai Rajan Bhattarai 1 min read
Rails-code

Add A Custom Computed Column To An Activeadmin Index Page

The default ActiveAdmin index lists raw columns. Real admin screens need derived values — a total from associated rows, a status badge, a link to a related record — and the column block

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Test Action Mailer Content With Rspec Matchers In Rails

Mailers break quietly — a renamed method in a template, a missing interpolation, a recipient list that silently resolves to nil. None of it surfaces until a customer says they never got the

Rajan Bhattarai Rajan Bhattarai 2 min read
Rails-code

Serialize Query Params Back Into A Url String In Rails

Filter forms, pagination links, and sort toggles all need to rebuild the current URL with one parameter changed and the rest preserved. Doing it with string concatenation breaks on the first array parameter

Rajan Bhattarai Rajan Bhattarai 1 min read
Page 1 of 2 Older Posts »
FirstDEV blog © 2026
Proudly published with Jekyll & using Jasper2
Latest Posts Twitter
FirstDEV blog

Check viewARU - Brand Newsletter!

Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀