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,
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.
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
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
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”,
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
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
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
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.
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;
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
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
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
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
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