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

Solutions

We solve problems, so you don't have to!

Ruby-code

Generate All Combinations Of Array Elements Without Repetition In Ruby

Picking every possible pair of players, every three-item bundle from a catalogue, every subset of feature flags — these are combinations, and Ruby has them built in. No manual nested loops required.

Rajan Bhattarai Rajan Bhattarai 2 min read
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
Ruby-code

Parse A Csv String Into An Array Of Hashes With Headers In Ruby

Uploaded spreadsheets and API exports arrive as CSV strings. Converting them into an array of hashes keyed by header name makes the rest of the code readable — row[:email] instead of row[3].

Rajan Bhattarai Rajan Bhattarai 1 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
Ruby-code

Count Unique Values Across Nested Arrays In Ruby Without Duplicates

Tags across a set of posts, permissions across a set of roles, skills across a team — the data arrives as an array of arrays and you need the distinct total, or the

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
Ruby-code

Remove Duplicate Hashes From An Array By A Specific Key In Ruby

uniq on an array of hashes compares whole hashes, so two records that share an id but differ in any other field both survive. Deduplicating by one key — an id, an email,

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
Page 1 of 4 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! 🚀