<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Write Software Well</title><description>A blog about software development done right, with a special focus on Ruby on Rails.</description><link>https://writesoftwarewell.com/</link><language>en-us</language><copyright>Copyright 2026 Write Software Well</copyright><managingEditor>akshay@typeangle.com (Akshay Khot)</managingEditor><webMaster>akshay@typeangle.com (Akshay Khot)</webMaster><lastBuildDate>Mon, 09 Nov 2026 22:40:22 +0000</lastBuildDate><atom:link href="https://writesoftwarewell.com/feed.xml" rel="self" type="application/rss+xml"/><item><title>How Claude Uses Tools to Get Data and Run Code in Your App</title><description>Claude can't query your database or run your code, but it can ask your app to on its behalf. In this post, we'll learn how Claude uses tools at the API level in a Rails app, with plain Ruby. It also covers server tools like web search, defining your own tools, the agent loop, and where MCP fits in.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>In the previous post, we saw <a href="https://writesoftwarewell.com/how-large-language-models-llms-work">how a large language model like Claude works</a>. Your application can use Claude by sending HTTP requests to the Claude API, which Anthropic runs. The model can't query your database, call your APIs, or run any of your code. All it can do is read the text you send it and write text back. Yet you've used AI features that look up records, search the web, or edit your code in a local repo. They're all built on a feature of the Claude API called <a href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">tool use</a>. With tool use, Claude doesn't run your code. It asks your app to run it, and your app decides whether to run it or not.</p>
<p>In this post, we'll build that tool exchange to learn what goes back and forth between your app and the Claude API so it can execute your code and access your data that it can't see otherwise. We'll start with server tools like web search, which Anthropic runs for you. Then we'll define a client tool that looks up a customer in our database, run it when Claude asks, and send the result back. Once that exchange makes sense, we'll build the loop that AI agents are built upon. At the end, we'll look at where MCP fits in that lets an agent like Claude Code run tools on your behalf.</p>
<h2 id="the-problem-tools-solve">The Problem Tools Solve</h2>
<p>Let's say we're building a support inbox app called Helpdesk. Its users are support reps: they read tickets from customers and reply to them. We want to add a chat sidebar where a support rep can ask questions in plain English, and our Rails app (Helpdesk) answers them using Claude. For example, a support rep John, is looking at a ticket from a customer named Jane. He types this into the sidebar:</p>
<blockquote>
<p>What plan is <a href="mailto:jane@example.com">jane@example.com</a> on, and does she have any other open tickets?</p>
</blockquote>
<p>Our Rails app sends John's question to the Claude API and shows him the reply. But Claude can't answer it. It has never seen our application database. It knows a lot about the world up to its training cutoff, but nothing about Jane, who is a customer record in your Helpdesk database.</p>
<p>To see why, it helps to remember what a language model is. It takes text in and predicts text out, one token at a time, and the API is stateless, so every request has to carry everything the model should know. The model has no access to anything outside that request: no database, no network, etc.</p>
<p>The simplest fix is to put the data in the request. Load Jane's record, format it as text, and send it along with John's question. That works well when you know ahead of time what the model will need, and it's the right approach for a lot of features. But here, we don't know which customer John will ask about until he asks it. We can't send every customer in the account with every request.</p>
<p>What we need is for the model to tell us what it needs, so we can fetch it from our database. Before the APIs had built-in support for this, people did it with a plain text convention. You'd write something like this in the system prompt for LLM:</p>
<pre data-language="text"><code class="code-inline language-text">If you need details about a customer, reply with exactly one line in this format,
and nothing else:

LOOKUP &lt;email&gt;

You&#39;ll receive the customer&#39;s details in the next message.</code></pre>
<p>Then you'd check every reply for that pattern:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">if</span> <span class="p">(</span><span class="n">match</span> <span class="o">=</span> <span class="n">reply</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sr">/\ALOOKUP (\S+@\S+)\z/</span><span class="p">))</span>
  <span class="n">customer</span> <span class="o">=</span> <span class="no">Customer</span><span class="o">.</span><span class="n">find_by</span><span class="p">(</span><span class="ss">email</span><span class="p">:</span> <span class="n">match</span><span class="o">[</span><span class="mi">1</span><span class="o">]</span><span class="p">)</span>
  <span class="c1"># ...send the details back as the next message</span>
<span class="k">end</span></code></pre>
<p>The model is predicting probable text, not following a protocol. Sometimes it replies <code>Sure! LOOKUP jane@example.com</code>, and the regex doesn't match. Sometimes it adds a trailing period, which becomes part of the email. Sometimes it writes the lookup line and then keeps going with a guess at the answer. And it just complicates the whole regex parsing workflow.</p>
<p>Tool use is this same idea, built into the model and the API. The model is trained to request tools in a specific format. The API recognizes that format, parses it, and hands it to you as JSON, with the tool's name and its arguments already separated. You don't have to write the regex to extract meaningful information, like the customer's name.</p>
<h2 id="what-is-a-tool">What is a Tool?</h2>
<p>A tool is a function that you describe to a language model, so that the model can ask for it to be run if and when needed. The tool description has three parts: a name, a sentence or two about what the function does and when to use it, and the type of the arguments it takes.</p>
<p>As mentioned earlier, the model can't run anything itself. When it decides it needs a tool, it replies with a request: &quot;please call <code>find_customer</code> with the email <code>jane@example.com</code>.&quot; Something outside the model, like your application runs the function and sends the result back in the next request. The model then uses that result to write its answer.</p>
<p>Here's that sequence for John's question, from the moment he asks to the moment he sees the answer:</p>
<pre data-language="text"><code class="code-inline language-text"> John               Our Rails app                       Claude (via the API)
  |                       |                                      |
  | &#34;What plan is Jane    |                                      |
  |  on?&#34;                 |                                      |
  |----------------------&gt;|                                      |
  |                       | 1. John&#39;s question                   |
  |                       |    + a description of find_customer  |
  |                       |-------------------------------------&gt;|
  |                       |                                      | Doesn&#39;t know
  |                       |                                      | Jane, so it
  |                       | 2. &#34;Please call find_customer        | asks for the
  |                       |     with jane@example.com&#34;           | tool
  |                       |&lt;-------------------------------------|
  |                       |                                      |
  |                       |--+                                   |
  |                       |  | 3. Runs find_customer,            |
  |                       |  |    which queries the database     |
  |                       |&lt;-+                                   |
  |                       |                                      |
  |                       | 4. John&#39;s question, the model&#39;s      |
  |                       |    request, and Jane&#39;s details       |
  |                       |-------------------------------------&gt;|
  |                       |                                      | Reads Jane&#39;s
  |                       | 5. &#34;Jane is on the Business plan...&#34; | details and
  |                       |&lt;-------------------------------------| writes the
  |                       |                                      | answer
  | &#34;Jane is on the       |                                      |
  |  Business plan...&#34;    |                                      |
  |&lt;----------------------|                                      |</code></pre>
<p>Steps 1 and 2 are one HTTP request and its response, and steps 4 and 5 are another. Step 3 happens entirely inside our app: Claude never touches the database. It only sees what our code chooses to send back in step number 4.</p>
<p>That's the purpose of a tool: <strong>it gives the model a way to get information it doesn't have, or to take an action it can't take, by asking our code to do it</strong>. Every AI feature that does more than generate text is built on this. When Claude searches the web, when Claude Code or Codex edits a file in your codebase, or when our sidebar looks up Jane's plan, the model is asking for a tool call and some code is running it.</p>
<p>The name makes it sound like the model reaches out to the tool which does things in the world. It doesn't. The model writes a structured request, and some code decides whether and how to carry it out. That code can live in two places, which gives us two kinds of tools:</p>
<ul>
<li><strong>Server tools</strong> are tools that Anthropic runs on its own servers, like web search. You mention the server tool you want in the API call, and Anthropic handles everything else.</li>
<li><strong>Client tools</strong> are tools that your app runs. You describe them, and when the model asks for one, your application code runs it and sends back the result.</li>
</ul>
<p>Jane's details live in our database, which Anthropic can't reach, so the customer lookup has to be a client tool. But server tools are the simpler kind, and they show the whole idea with the least code, so we'll start there.</p>
<p>Before we do, one piece of terminology. In the Claude API, every message in a conversation has a role, and there are only two: <code>user</code> and <code>assistant</code>. Messages the model writes have the role <code>assistant</code>. Everything else has the role <code>user</code>. These are roles in the API, not people. In our example, John is the person using our Rails app typing the question, our Rails app is what sends the requests to Anthropic API, and Claude is the model writing the <code>assistant</code> messages. John never talks to the API directly.</p>
<h2 id="server-tools">Server Tools</h2>
<p>Say a business customer in Germany writes in. They've been charged VAT on their invoice, and they say they shouldn't be, because they gave us their VAT ID. John isn't a tax expert, and he doesn't want to guess. He asks the sidebar to find out whether the customer is right and what we'd need from them. Claude may know the general rules from its training data, but tax rules change, its knowledge stops at its training cutoff, and John needs current sources he can check before replying to a paying customer. This is what Anthropic's web search tool is for.</p>
<p>Here's a request that turns on web search:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">client</span> <span class="o">=</span> <span class="no">Anthropic</span><span class="o">::</span><span class="no">Client</span><span class="o">.</span><span class="n">new</span>

<span class="no">WEB_SEARCH</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">type</span><span class="p">:</span> <span class="s2">&#34;web_search_20250305&#34;</span><span class="p">,</span> <span class="nb">name</span><span class="p">:</span> <span class="s2">&#34;web_search&#34;</span><span class="p">,</span> <span class="ss">max_uses</span><span class="p">:</span> <span class="mi">3</span> <span class="p">}</span>

<span class="n">messages</span> <span class="o">=</span> <span class="o">[</span>
  <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="s2">&#34;A customer in Germany says we should not charge them VAT because they gave us their VAT ID. Are they right, and what do we need from them?&#34;</span> <span class="p">}</span>
<span class="o">]</span>

<span class="n">reply</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">messages</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
  <span class="ss">model</span><span class="p">:</span> <span class="s2">&#34;claude-sonnet-5-5&#34;</span><span class="p">,</span> <span class="ss">max_tokens</span><span class="p">:</span> <span class="mi">16_000</span><span class="p">,</span> <span class="ss">tools</span><span class="p">:</span> <span class="o">[</span> <span class="no">WEB_SEARCH</span> <span class="o">]</span><span class="p">,</span> <span class="ss">messages</span><span class="p">:</span> <span class="n">messages</span>
<span class="p">)</span></code></pre>
<p><code>model</code> picks which Claude model answers, <code>max_tokens</code> caps the length of its reply, and <code>messages</code> is the conversation so far. The only new thing compared to a plain request is <code>tools</code>, an array of tool definitions. You can pass as many as you like, and the model chooses among them, or decides it doesn't need any. Here, the array has a single entry: the web search tool.</p>
<p>A server tool is defined by its <code>type</code>, not by a description and a schema. Anthropic has already written those, and the model has been trained on them. The date in the type is a version: <code>web_search_20250305</code> is the basic web search tool, and newer versions (<code>web_search_20260209</code> and <code>web_search_20260318</code>, as of November 2026) add features like letting the model filter results with code before reading them. <code>max_uses</code> caps how many searches the model can run while answering this one message.</p>
<p>The response is a single assistant message, and its <code>content</code> array tells what happened, in order:</p>
<ul>
<li>A short <code>text</code> block, in which the model says it's going to search.</li>
<li>A <code>server_tool_use</code> block. This is the model's request: it wants the <code>web_search</code> tool, with a search query it wrote itself.</li>
<li>A <code>web_search_tool_result</code> block, holding the results Anthropic got back: each page's URL, its title, and its content.</li>
<li>One or more <code>text</code> blocks with the answer.</li>
</ul>
<p>Here's what that looks like, with the long values shortened:</p>
<pre data-language="json"><code class="code-inline language-json"><span class="p">{</span>
  <span class="nt">&#34;role&#34;</span><span class="p">:</span> <span class="s2">&#34;assistant&#34;</span><span class="p">,</span>
  <span class="nt">&#34;stop_reason&#34;</span><span class="p">:</span> <span class="s2">&#34;end_turn&#34;</span><span class="p">,</span>
  <span class="nt">&#34;content&#34;</span><span class="p">:</span> <span class="p">[</span>
    <span class="p">{</span> <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;text&#34;</span><span class="p">,</span> <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;I&#39;ll look up the current EU VAT rules for business customers.&#34;</span> <span class="p">},</span>
    <span class="p">{</span>
      <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;server_tool_use&#34;</span><span class="p">,</span>
      <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;srvtoolu_01WYG3...&#34;</span><span class="p">,</span>
      <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;web_search&#34;</span><span class="p">,</span>
      <span class="nt">&#34;input&#34;</span><span class="p">:</span> <span class="p">{</span> <span class="nt">&#34;query&#34;</span><span class="p">:</span> <span class="s2">&#34;EU VAT reverse charge B2B digital services VAT ID&#34;</span> <span class="p">}</span>
    <span class="p">},</span>
    <span class="p">{</span>
      <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;web_search_tool_result&#34;</span><span class="p">,</span>
      <span class="nt">&#34;tool_use_id&#34;</span><span class="p">:</span> <span class="s2">&#34;srvtoolu_01WYG3...&#34;</span><span class="p">,</span>
      <span class="nt">&#34;content&#34;</span><span class="p">:</span> <span class="p">[</span>
        <span class="p">{</span>
          <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;web_search_result&#34;</span><span class="p">,</span>
          <span class="nt">&#34;url&#34;</span><span class="p">:</span> <span class="s2">&#34;https://europa.eu/youreurope/business/taxation/vat/cross-border-vat/index_en.htm&#34;</span><span class="p">,</span>
          <span class="nt">&#34;title&#34;</span><span class="p">:</span> <span class="s2">&#34;Cross-border VAT - Your Europe&#34;</span>
        <span class="p">}</span>
      <span class="p">]</span>
    <span class="p">},</span>
    <span class="p">{</span>
      <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;text&#34;</span><span class="p">,</span>
      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Most likely, yes. For services sold to a business with a valid VAT ID, the reverse charge usually applies, ...&#34;</span><span class="p">,</span>
      <span class="nt">&#34;citations&#34;</span><span class="p">:</span> <span class="p">[</span>
        <span class="p">{</span>
          <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;web_search_result_location&#34;</span><span class="p">,</span>
          <span class="nt">&#34;url&#34;</span><span class="p">:</span> <span class="s2">&#34;https://europa.eu/youreurope/business/taxation/vat/cross-border-vat/index_en.htm&#34;</span><span class="p">,</span>
          <span class="nt">&#34;title&#34;</span><span class="p">:</span> <span class="s2">&#34;Cross-border VAT - Your Europe&#34;</span>
        <span class="p">}</span>
      <span class="p">]</span>
    <span class="p">}</span>
  <span class="p">],</span>
  <span class="nt">&#34;usage&#34;</span><span class="p">:</span> <span class="p">{</span> <span class="nt">&#34;input_tokens&#34;</span><span class="p">:</span> <span class="mi">6039</span><span class="p">,</span> <span class="nt">&#34;output_tokens&#34;</span><span class="p">:</span> <span class="mi">931</span><span class="p">,</span> <span class="nt">&#34;server_tool_use&#34;</span><span class="p">:</span> <span class="p">{</span> <span class="nt">&#34;web_search_requests&#34;</span><span class="p">:</span> <span class="mi">1</span> <span class="p">}</span> <span class="p">}</span>
<span class="p">}</span></code></pre>
<p>The <code>tool_use_id</code> on the result matches the <code>id</code> of the <code>server_tool_use</code> block, which is how you can tell which result answers which request.</p>
<p>The response's <code>stop_reason</code> is <code>&quot;end_turn&quot;</code>, which means the model finished its answer and there's nothing left for your code to do. You take the text and show it to John. Everything, including the search, happened inside one HTTP request.</p>
<p>Look at what happened between the request and the response. <strong>The model started writing, decided it needed to search, and wrote a request for the tool.</strong> Anthropic's servers saw that request, paused the model, ran the search, added the results to the model's input, and let the model continue. The model read the results and wrote the answer. If the first search wasn't good enough, it could have searched again, up to the <code>max_uses</code> limit, all before the response came back. Anthropic's docs call this the server-side loop. Keep it in mind, because later in this post we'll build the same loop ourselves.</p>
<p>Web search isn't the only server tool. As of November 2026, Anthropic also runs web fetch (read the full content of a specific URL), code execution (run Python and Bash in a sandbox, useful for analyzing a CSV a customer attached), and tool search (find the right tool among hundreds without putting all their definitions in every request). The <a href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference">tool reference</a> lists them all. There's also a middle category: tools like bash and the text editor, where Anthropic defines the tool and has trained the model on it, but your app runs it. Coding agents use those.</p>
<p>Server tools are convenient, but they can only reach what Anthropic can reach: the public internet and a sandbox. They can't reach your database. For that, we need a tool of our own.</p>
<h2 id="client-tools-allow-claude-to-access-your-app-data-and-code">Client Tools: Allow Claude to Access Your App Data and Code</h2>
<p>A client tool is a function that you define in your code and your app runs. When Claude asks for one, the API doesn't run it. It stops and hands the request back to your Rails app, and your Ruby code decides what to do. That code can do anything the rest of your app can: query Active Record models, call an internal service, or update a record. Claude never sees that code. It sees only the tool's description, and later, whatever result your code sends back.</p>
<p>That's what John's question needs. Jane's plan and her open tickets are rows in our database, and only our app can read them. So we'll give Claude a <code>find_customer</code> tool, and our app will run the query whenever Claude asks for it.</p>
<p>Using a client tool takes two steps. First, we describe the tool, so Claude knows it exists and when to use it. Then we handle the exchange: notice when Claude asks for the tool, run it, and send the result back. This section covers the first step, and the next section covers the second.</p>
<p>A client tool definition has the three parts from earlier: a name, a description, and a schema for its input. Here's one for our customer lookup:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="no">FIND_CUSTOMER</span> <span class="o">=</span> <span class="p">{</span>
  <span class="nb">name</span><span class="p">:</span> <span class="s2">&#34;find_customer&#34;</span><span class="p">,</span>
  <span class="ss">description</span><span class="p">:</span> <span class="o">&lt;&lt;~</span><span class="no">TEXT</span><span class="o">.</span><span class="n">squish</span><span class="p">,</span>
    <span class="no">Looks</span> <span class="n">up</span> <span class="n">a</span> <span class="n">customer</span> <span class="n">of</span> <span class="n">this</span> <span class="n">support</span> <span class="n">team</span> <span class="n">by</span> <span class="n">their</span> <span class="n">email</span> <span class="n">address</span><span class="o">.</span>
    <span class="no">Returns</span> <span class="n">the</span> <span class="n">customer</span><span class="s1">&#39;s name, their plan, and the subjects of their open tickets.
</span><span class="s1">    Use it whenever a question is about a specific customer and their details
</span><span class="s1">    aren&#39;</span><span class="n">t</span> <span class="n">already</span> <span class="k">in</span> <span class="n">the</span> <span class="n">conversation</span><span class="o">.</span> <span class="no">It</span> <span class="n">doesn</span><span class="s1">&#39;t return billing history or payments.
</span><span class="s1">  TEXT
</span><span class="s1">  input_schema: {
</span><span class="s1">    type: &#34;object&#34;,
</span><span class="s1">    properties: {
</span><span class="s1">      email: { type: &#34;string&#34;, description: &#34;The customer&#39;</span><span class="n">s</span> <span class="n">email</span> <span class="n">address</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">g</span><span class="o">.</span> <span class="n">jane</span><span class="vi">@example</span><span class="o">.</span><span class="n">com</span><span class="s2">&#34; }
</span><span class="s2">    },
</span><span class="s2">    required: [ &#34;</span><span class="n">email</span><span class="s2">&#34; ]
</span><span class="s2">  }
</span><span class="s2">}</span></code></pre>
<p>The <code>name</code> is how the model will refer to the tool when it asks for it. It has to be letters, numbers, underscores, or hyphens. Name tools after what they do, the same way you'd name a method.</p>
<p>The <code>description</code> tells the model what the tool does or when to use it. Anthropic's docs call detailed descriptions &quot;by far the most important factor in tool performance&quot; and suggest at least three to four sentences per tool. Notice that the description above says what the tool returns, when to use it, and what it doesn't do. Without it, if John asked about Jane's last payment, the model might call <code>find_customer</code> and hope the answer is in there.</p>
<p>The <code>input_schema</code> describes the arguments. This one says the input is an object with a single required string, <code>email</code>.</p>
<h3 id="what-the-model-actually-sees">What The Model Actually Sees</h3>
<p>The model only ever sees text. When you send tools with a request, the API turns them into text and adds it to the system prompt. Anthropic documents the template it uses. It starts like this:</p>
<pre data-language="text"><code class="code-inline language-text">In this environment you have access to a set of tools you can use to answer the user&#39;s question.
...
Here are the functions available in JSONSchema format:
{{ TOOL DEFINITIONS IN JSON SCHEMA }}
{{ USER SYSTEM PROMPT }}</code></pre>
<p>Your tool definitions are pasted in as JSON, followed by your own system prompt. From the model's point of view, a tool is a paragraph of instructions describing a function it's allowed to ask for. (Server tools work the same way. The only difference is that Anthropic wrote their definitions.)</p>
<p>When the model decides to use a tool, it's doing the same thing it always does: predicting the next token. Through fine-tuning and reinforcement learning, it has learned that when a question matches a tool's description, the most probable continuation is a tool request in a specific format. The Claude API spots that format in the output, stops generation, and converts it into JSON for you.</p>
<p>This has two consequences:</p>
<p><strong>Tools cost tokens on every request.</strong> The definitions are part of the prompt, so you pay for them on every call, whether the model uses them or not. On top of your definitions, the API adds its own tool-use instructions, which Anthropic lists at 286 tokens for Claude Sonnet 5.5 (as of November 2026). Ten tools with good descriptions can easily add a couple of thousand tokens to every request.</p>
<p><strong>The model can get it wrong.</strong> It picks tools and fills in arguments by prediction, the same way it writes everything else. It might pick the wrong tool, call a tool it doesn't need, or invent an argument value. We'll come back to this.</p>
<h2 id="the-tool-use-exchange">The Tool Use Exchange</h2>
<p>With a server tool, the whole exchange happened inside one request. With a client tool, Anthropic can't run the tool, which resides in your application, so the API stops and hands the request back to you. Here's the full exchange, from the API's point of view:</p>
<ol>
<li>Request 1: John's question, plus the tool definitions.</li>
<li>Response 1: a <code>tool_use</code> block asking for <code>find_customer</code>.</li>
<li>Your code runs <code>find_customer</code>.</li>
<li>Request 2: John's question, the model's <code>tool_use</code> block, and your <code>tool_result</code>, plus the tool definitions again.</li>
<li>Response 2: the answer.</li>
</ol>
<p>Let's go through each step.</p>
<h3 id="the-first-request">The First Request</h3>
<p>We send John's question the same way, with our tool in the <code>tools</code> array:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">messages</span> <span class="o">=</span> <span class="o">[</span>
  <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="s2">&#34;What plan is jane@example.com on, and does she have any other open tickets?&#34;</span> <span class="p">}</span>
<span class="o">]</span>

<span class="n">reply</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">messages</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
  <span class="ss">model</span><span class="p">:</span> <span class="s2">&#34;claude-sonnet-5-5&#34;</span><span class="p">,</span> <span class="ss">max_tokens</span><span class="p">:</span> <span class="mi">16_000</span><span class="p">,</span> <span class="ss">tools</span><span class="p">:</span> <span class="o">[</span> <span class="no">FIND_CUSTOMER</span> <span class="o">]</span><span class="p">,</span> <span class="ss">messages</span><span class="p">:</span> <span class="n">messages</span>
<span class="p">)</span></code></pre>
<p>Here's the kind of response you get back:</p>
<pre data-language="json"><code class="code-inline language-json"><span class="p">{</span>
  <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;msg_01Aq9w938a90dw8q&#34;</span><span class="p">,</span>
  <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;message&#34;</span><span class="p">,</span>
  <span class="nt">&#34;role&#34;</span><span class="p">:</span> <span class="s2">&#34;assistant&#34;</span><span class="p">,</span>
  <span class="nt">&#34;model&#34;</span><span class="p">:</span> <span class="s2">&#34;claude-sonnet-5-5&#34;</span><span class="p">,</span>
  <span class="nt">&#34;stop_reason&#34;</span><span class="p">:</span> <span class="s2">&#34;tool_use&#34;</span><span class="p">,</span>
  <span class="nt">&#34;content&#34;</span><span class="p">:</span> <span class="p">[</span>
    <span class="p">{</span>
      <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;text&#34;</span><span class="p">,</span>
      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;I&#39;ll look up that customer.&#34;</span>
    <span class="p">},</span>
    <span class="p">{</span>
      <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;tool_use&#34;</span><span class="p">,</span>
      <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;toolu_01A09q90qw90lq917835lq9&#34;</span><span class="p">,</span>
      <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;find_customer&#34;</span><span class="p">,</span>
      <span class="nt">&#34;input&#34;</span><span class="p">:</span> <span class="p">{</span> <span class="nt">&#34;email&#34;</span><span class="p">:</span> <span class="s2">&#34;jane@example.com&#34;</span> <span class="p">}</span>
    <span class="p">}</span>
  <span class="p">]</span>
<span class="p">}</span></code></pre>
<p>Compare this with the web search response. There are three differences.</p>
<p><code>stop_reason</code> is <code>&quot;tool_use&quot;</code>, not <code>&quot;end_turn&quot;</code>. The model stopped halfway because it's waiting on you. <strong>This is the field your code checks to decide what to do next.</strong></p>
<p>The request is a <code>tool_use</code> block, not a <code>server_tool_use</code> block. The block holds the request itself: <code>name</code> is the tool the model wants, <code>input</code> is a hash matching the tool's schema, and <code>id</code> identifies this particular call. You'll need that <code>id</code> in a minute.</p>
<p>There's no result block after it, because we have not run the tool yet and no query is executed. The model hasn't looked up Jane. It has written down, in a format your code can parse, that it would like you to run the tool. If you ignored this response, Jane's record would never be touched.</p>
<p>As before, the first <code>text</code> block is just the model saying what it's doing. Your code shouldn't depend on it being there or saying anything in particular. Sometimes the model says nothing before calling a tool, and sometimes it explains at length.</p>
<p>That JSON is what travels over the wire. The SDK hands it to you as Ruby objects instead of a hash. <code>reply.stop_reason</code> returns the symbol <code>:tool_use</code>, and <code>reply.content</code> is an array, and so on.</p>
<h3 id="running-the-tool">Running The Tool</h3>
<p>Running the tool is ordinary Rails code. For this example, the Helpdesk app has accounts, and each account has customers. A customer belongs to a plan and has many tickets, and tickets have an <code>open</code> scope:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">run_tool</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">input</span><span class="p">)</span>
  <span class="k">case</span> <span class="nb">name</span>
  <span class="k">when</span> <span class="s2">&#34;find_customer&#34;</span>
    <span class="n">customer</span> <span class="o">=</span> <span class="no">Current</span><span class="o">.</span><span class="n">account</span><span class="o">.</span><span class="n">customers</span><span class="o">.</span><span class="n">find_by</span><span class="p">(</span><span class="ss">email</span><span class="p">:</span> <span class="n">input</span><span class="o">[</span><span class="ss">:email</span><span class="o">]</span><span class="p">)</span>
    <span class="k">return</span> <span class="s2">&#34;No customer with the email </span><span class="si">#{</span><span class="n">input</span><span class="o">[</span><span class="ss">:email</span><span class="o">]</span><span class="si">}</span><span class="s2"> exists in this account.&#34;</span> <span class="k">unless</span> <span class="n">customer</span>

    <span class="p">{</span>
      <span class="nb">name</span><span class="p">:</span> <span class="n">customer</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
      <span class="ss">plan</span><span class="p">:</span> <span class="n">customer</span><span class="o">.</span><span class="n">plan</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
      <span class="ss">open_tickets</span><span class="p">:</span> <span class="n">customer</span><span class="o">.</span><span class="n">tickets</span><span class="o">.</span><span class="n">open</span><span class="o">.</span><span class="n">pluck</span><span class="p">(</span><span class="ss">:subject</span><span class="p">)</span>
    <span class="p">}</span><span class="o">.</span><span class="n">to_json</span>
  <span class="k">else</span>
    <span class="k">raise</span> <span class="no">ArgumentError</span><span class="p">,</span> <span class="s2">&#34;Unknown tool: </span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>The <code>case</code> maps tool names to code. With just one tool to find customers, it's a single branch. With ten tools, you'd want something more organized than a <code>case</code> statement, which is why I'm planning to write another post that will show code organization with tools.</p>
<blockquote>
<p>Look at <code>Current.account.customers.find_by</code>. It would be easy to write <code>Customer.find_by(email: input[:email])</code> here. But the email came from the model, and the model got it from text that John typed. <strong>Treat tool input exactly like params from a form.</strong> Scope every lookup to what the current user is allowed to see. If a support rep from one account could get the sidebar to look up an email belonging to another account, <code>Customer.find_by</code> would hand over that customer's details. This is standard multi-tenant practice in Rails. But important to remember that <strong>the model is not an authorization layer</strong>.</p>
</blockquote>
<p>When the customer isn't found, the method returns a plain sentence saying so. The result goes back to the model as text, and a clear sentence gives it something useful to tell John. Returning <code>nil</code>, or an empty string, would leave it guessing.</p>
<p>When a customer is found, the result is a JSON string. It doesn't have to be. The model reads the result as text, so you could also return a few formatted lines. Structured JSON data is preferred because models read it well and <code>to_json</code> is one call. Whatever format you choose, include only the fields the model needs. Every field you return is more tokens in the context, and a customer record with 40 columns makes the actually relevant fields harder to find.</p>
<h3 id="sending-the-result-back">Sending The Result Back</h3>
<p>Now we need to tell the model what we found. Since the API is stateless, that means sending the whole conversation again, with two new messages on the end:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Add the model&#39;s reply to the conversation, exactly as we received it.</span>
<span class="c1"># It contains the tool_use block, so the model will see its own request.</span>
<span class="n">messages</span> <span class="o">&lt;&lt;</span> <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;assistant&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="n">reply</span><span class="o">.</span><span class="n">content</span> <span class="p">}</span>

<span class="c1"># Find every tool request in the reply (there can be more than one),</span>
<span class="c1"># run each tool, and wrap its output in a tool_result block.</span>
<span class="n">tool_results</span> <span class="o">=</span> <span class="n">reply</span><span class="o">.</span><span class="n">content</span><span class="o">.</span><span class="n">select</span> <span class="p">{</span> <span class="n">it</span><span class="o">.</span><span class="n">type</span> <span class="o">==</span> <span class="ss">:tool_use</span> <span class="p">}</span><span class="o">.</span><span class="n">map</span> <span class="k">do</span> <span class="o">|</span><span class="n">tool_use</span><span class="o">|</span>
  <span class="p">{</span>
    <span class="ss">type</span><span class="p">:</span> <span class="s2">&#34;tool_result&#34;</span><span class="p">,</span>
    <span class="c1"># Ties this result to the request it answers.</span>
    <span class="ss">tool_use_id</span><span class="p">:</span> <span class="n">tool_use</span><span class="o">.</span><span class="n">id</span><span class="p">,</span>
    <span class="c1"># Our Ruby code runs here. For find_customer, this is Jane&#39;s details as JSON.</span>
    <span class="ss">content</span><span class="p">:</span> <span class="n">run_tool</span><span class="p">(</span><span class="n">tool_use</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">tool_use</span><span class="o">.</span><span class="n">input</span><span class="p">)</span>
  <span class="p">}</span>
<span class="k">end</span>

<span class="c1"># Send the results back in a user message. &#34;user&#34; is the API role for</span>
<span class="c1"># anything the model didn&#39;t write, not John.</span>
<span class="n">messages</span> <span class="o">&lt;&lt;</span> <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="n">tool_results</span> <span class="p">}</span>

<span class="c1"># The second request: the whole conversation so far, and the same tools.</span>
<span class="n">final</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">messages</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
  <span class="ss">model</span><span class="p">:</span> <span class="s2">&#34;claude-sonnet-5-5&#34;</span><span class="p">,</span> <span class="ss">max_tokens</span><span class="p">:</span> <span class="mi">16_000</span><span class="p">,</span> <span class="ss">tools</span><span class="p">:</span> <span class="o">[</span> <span class="no">FIND_CUSTOMER</span> <span class="o">]</span><span class="p">,</span> <span class="ss">messages</span><span class="p">:</span> <span class="n">messages</span>
<span class="p">)</span>

<span class="c1"># This time the stop_reason is :end_turn, and the answer is in a text block.</span>
<span class="n">final</span><span class="o">.</span><span class="n">content</span><span class="o">.</span><span class="n">find</span> <span class="p">{</span> <span class="n">it</span><span class="o">.</span><span class="n">type</span> <span class="o">==</span> <span class="ss">:text</span> <span class="p">}</span><span class="o">.</span><span class="n">text</span>
<span class="c1"># =&gt; &#34;Jane is on the Business plan. She has two other open tickets: ...&#34;</span></code></pre>
<p>First, we append the model's reply to the conversation as an <code>assistant</code> message. We pass <code>reply.content</code> back exactly as we received it, every block, untouched. That includes the <code>tool_use</code> block, so the model can see its own request in the next turn. It can also include thinking blocks on models that reason before answering, and the API requires those to come back unmodified alongside tool results.</p>
<p>Next, we build a <code>tool_result</code> block for each <code>tool_use</code> block. The model can ask for several tools at once (more on that soon), so we <code>select</code> all of them rather than assuming there's one. Each result has a <code>tool_use_id</code> that matches the <code>id</code> of the request it answers. That's how the model knows which result belongs to which request.</p>
<p>Then we send the results in a <code>user</code> message. Remember that <code>user</code> is a role in the API, not John. The API has only two roles, and anything the model didn't write itself goes on the <code>user</code> side. The <code>type: &quot;tool_result&quot;</code> is what tells the model this is a tool's output and not something John typed.</p>
<p>There are a couple of rules here, and the API returns an error if you break them. The tool result message has to come immediately after the <code>assistant</code> message that requested the tools, with nothing in between. And within that <code>user</code> message, the <code>tool_result</code> blocks have to come first. If you want to add a text note, it goes after the results.</p>
<p>Finally, we call <code>client.messages.create</code> again with the longer conversation. This time the model has Jane's details in its context, and it writes the answer. The <code>stop_reason</code> is <code>&quot;end_turn&quot;</code>, and our app shows the answer to John.</p>
<h3 id="the-exchange-step-by-step">The Exchange, Step By Step</h3>
<p>Here's the same five-step exchange again, now with what actually travels in each step.</p>
<ol>
<li><strong>Request 1.</strong> Our app sends <code>messages</code> with one <code>user</code> message holding John's question, and <code>tools</code> holding the <code>find_customer</code> definition. The API turns the definition into text in the system prompt, and the model reads both.</li>
<li><strong>Response 1.</strong> The model predicts that the best continuation is a request for <code>find_customer</code>. The API sees it, stops generation, and returns a <code>tool_use</code> block with an <code>id</code>, the tool <code>name</code>, and the <code>input</code> hash. The <code>stop_reason</code> is <code>&quot;tool_use&quot;</code>. Our app doesn't show anything to John yet.</li>
<li><strong>Our code runs the tool.</strong> We read <code>name</code> and <code>input</code> from the <code>tool_use</code> block, run <code>Current.account.customers.find_by</code>, and turn the result into a string. Nothing about this step involves the API. It's a plain database query, and it's the only step where anything actually happens to our data.</li>
<li><strong>Request 2.</strong> Our app sends <code>messages</code> again, now with three entries: John's question as a <code>user</code> message, the model's reply (including the <code>tool_use</code> block) as an <code>assistant</code> message, and a <code>user</code> message holding a <code>tool_result</code> block whose <code>tool_use_id</code> matches the request's <code>id</code>. We send the same <code>tools</code> again, since the API remembers nothing between requests.</li>
<li><strong>Response 2.</strong> The model reads the whole conversation, including Jane's details from the tool result, and writes the answer. The <code>stop_reason</code> is <code>&quot;end_turn&quot;</code>. Our app shows the text to John.</li>
</ol>
<p>John asked one question, and our app made two API calls. Because request 2 contains everything from request 1, you pay for those input tokens twice. That's worth knowing when you estimate the cost of a feature that uses tools.</p>
<p>Notice also what the model never did: <strong>it did not touch the database, and it never saw our code</strong>. It saw a description of a function, asked for it in a specific format, and later saw a string that our code chose to send. Your Rails app made every decision about what to actually run.</p>
<h2 id="letting-model-ask-again-with-agent-loop">Letting Model Ask Again with Agent Loop</h2>
<p>What if answering needs more than one lookup? Say John asks &quot;Which of Jane's open tickets has been waiting the longest, and what did she last say on it?&quot; Let's give the model a second tool, <code>get_ticket_messages</code>, which takes a ticket ID and returns its messages. Now the model needs to look up Jane, find the oldest open ticket, then ask for that ticket's messages. It doesn't know the ticket ID until it has seen the first result, so it can't ask for both at once.</p>
<p>The fix is to keep going as long as the model keeps asking:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># The value of `break` becomes the value of `loop`, so `final`</span>
<span class="c1"># ends up holding the model&#39;s last reply.</span>
<span class="n">final</span> <span class="o">=</span> <span class="kp">loop</span> <span class="k">do</span>
  <span class="c1"># Send the whole conversation so far, along with every tool the model can use.</span>
  <span class="n">reply</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">messages</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
    <span class="ss">model</span><span class="p">:</span> <span class="s2">&#34;claude-sonnet-5-5&#34;</span><span class="p">,</span> <span class="ss">max_tokens</span><span class="p">:</span> <span class="mi">16_000</span><span class="p">,</span> <span class="ss">tools</span><span class="p">:</span> <span class="no">TOOLS</span><span class="p">,</span> <span class="ss">messages</span><span class="p">:</span> <span class="n">messages</span>
  <span class="p">)</span>

  <span class="c1"># If the model didn&#39;t ask for a tool, it has its answer. Stop here.</span>
  <span class="k">break</span> <span class="n">reply</span> <span class="k">unless</span> <span class="n">reply</span><span class="o">.</span><span class="n">stop_reason</span> <span class="o">==</span> <span class="ss">:tool_use</span>

  <span class="c1"># Otherwise, add the model&#39;s tool request to the conversation, exactly as we received it...</span>
  <span class="n">messages</span> <span class="o">&lt;&lt;</span> <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;assistant&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="n">reply</span><span class="o">.</span><span class="n">content</span> <span class="p">}</span>

  <span class="c1"># ...run every tool it asked for, and add the results. Then go around again.</span>
  <span class="n">messages</span> <span class="o">&lt;&lt;</span> <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="n">tool_results_for</span><span class="p">(</span><span class="n">reply</span><span class="p">)</span> <span class="p">}</span>
<span class="k">end</span></code></pre>
<p><code>TOOLS</code> is the array of both tool definitions, and <code>tool_results_for</code> is the <code>select</code> and <code>map</code> from the previous section, pulled into a method. Each time around the loop, we send the conversation to Claude. If the model asked for tools, we run them, add the results to the conversation, and go around again. As soon as it stops with something other than <code>&quot;tool_use&quot;</code>, which usually means it has its answer, <code>break reply</code> ends the loop and hands that last reply to <code>final</code>.</p>
<p>Here's how John's question would play out:</p>
<ol>
<li><strong>Request 1</strong> carries John's question. The model replies with a <code>tool_use</code> block for <code>find_customer</code> with Jane's email. Our loop runs it and gets Jane's plan and her open tickets, each with an ID and a creation date.</li>
<li><strong>Request 2</strong> carries the conversation so far, including that result. The model reads the ticket list, works out that ticket 4812 is the oldest, and replies with a <code>tool_use</code> block for <code>get_ticket_messages</code> with <code>ticket_id: 4812</code>. Our loop runs that too.</li>
<li><strong>Request 3</strong> carries everything, including the ticket's messages. The model now has what it needs, writes the answer, and stops with <code>&quot;end_turn&quot;</code>. The <code>while</code> condition is false, and the loop ends.</li>
</ol>
<p>Our code never decided to look up the customer first and the ticket second. It didn't know which ticket to fetch, or how many steps the question would take. The model made each of those decisions, one response at a time, based on the results it had seen so far. Our loop only did two things: ran whatever the model asked for, and sent the results back.</p>
<p><strong>Those few lines are the core of every AI agent.</strong> An agent is a model, some tools, and a loop that runs until the model says it's done. The model decides what to do next, the loop carries it out, and the result goes back to the model so it can decide again. Anthropic's <a href="https://www.anthropic.com/engineering/building-effective-agents">Building Effective Agents</a> says that agents &quot;are typically just LLMs using tools based on environmental feedback in a loop.&quot;</p>
<p>We've already seen this loop once in this post. The web search tool ran the same loop on Anthropic's servers: the model asked for a search, Anthropic ran it, fed the results back, and the model decided whether to search again or answer. The only difference is who runs the tools. A coding agent like Claude Code is this loop too, with tools for reading files, editing them, and running shell commands, and a model that keeps asking for them until the task is done.</p>
<p>Everything else you hear about agents is built around this loop: you can add iteration limits so it can't run forever, have budgets, let a person approve risky calls before they run, add checks to survive a deploy halfway through.</p>
<h2 id="handle-errors">Handle Errors</h2>
<p>Tools fail like any other code. If <code>find_customer</code> raises an exception, the model is still waiting for a <code>tool_result</code> for its request, and the API rejects the next request if one is missing. So send a result anyway, and tell the model that the call failed. A <code>tool_result</code> can carry an <code>is_error</code> flag for this:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">tool_result</span><span class="p">(</span><span class="n">tool_use</span><span class="p">)</span>
  <span class="p">{</span> <span class="ss">type</span><span class="p">:</span> <span class="s2">&#34;tool_result&#34;</span><span class="p">,</span> <span class="ss">tool_use_id</span><span class="p">:</span> <span class="n">tool_use</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="n">run_tool</span><span class="p">(</span><span class="n">tool_use</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">tool_use</span><span class="o">.</span><span class="n">input</span><span class="p">)</span> <span class="p">}</span>
<span class="k">rescue</span> <span class="o">=&gt;</span> <span class="n">error</span>
  <span class="no">Rails</span><span class="o">.</span><span class="n">error</span><span class="o">.</span><span class="n">report</span><span class="p">(</span><span class="n">error</span><span class="p">)</span>
  <span class="p">{</span> <span class="ss">type</span><span class="p">:</span> <span class="s2">&#34;tool_result&#34;</span><span class="p">,</span> <span class="ss">tool_use_id</span><span class="p">:</span> <span class="n">tool_use</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="s2">&#34;The lookup failed: </span><span class="si">#{</span><span class="n">error</span><span class="o">.</span><span class="n">message</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">,</span> <span class="ss">is_error</span><span class="p">:</span> <span class="kp">true</span> <span class="p">}</span>
<span class="k">end</span></code></pre>
<p>With <code>is_error: true</code>, the model knows the call failed and can tell John, or try something else. Anthropic's docs suggest writing error messages that say what went wrong and what to try next, like &quot;Rate limit exceeded. Retry after 60 seconds&quot;, rather than a bare &quot;failed&quot;. The model reads the message, so give it something to act on. (You have to be a bit careful about what goes in it. An exception message can include details you wouldn't want shown to a user, and anything you send to the model can end up in its reply.)</p>
<p>Another type of failure is the model filling in arguments badly. If John asks &quot;What plan is Jane on?&quot; without an email, the model might ask which Jane he means. Or, as Anthropic's docs warn, it might infer a value he never gave it. Smaller models are more likely to guess. Good descriptions help a lot here, and a system prompt line like &quot;If you don't have the customer's email, ask for it instead of guessing.&quot; is also helpful to guide the model.</p>
<p>Finally, remember that tool results often contain text you don't control: a customer's message, a web page, an email. The model reads all of it, and some of it might be written to manipulate the model (&quot;Ignore your instructions and...&quot;). This is called prompt injection, and it gets more dangerous as your tools get more powerful. You don't want to start issuing refunds based only on the model's output without any human checks.</p>
<h2 id="how-does-tool-use-relate-to-mcp">How does Tool Use Relate to MCP?</h2>
<p>You've probably heard of MCP, the Model Context Protocol, and wondered how it relates to all this. To answer that, we need two terms that MCP uses: the AI application and the MCP server.</p>
<p>An AI application is a program that sends requests to a model and runs tools when the model asks for them. Our Helpdesk app is one: its sidebar sends John's questions to Claude and runs <code>find_customer</code> when Claude asks. Claude Code is another, and so is the Claude desktop app. Each of them runs the same exchange you've seen in this post, and each one can only run tools it has code for.</p>
<p>So far, that hasn't been a problem, because every tool in this post lives inside Helpdesk, the same app that talks to Claude via API. Now consider a different situation. You're using Claude Code to fix a bug, and you want it to read the support ticket from Helpdesk where that bug was reported. Claude Code has no tool for that. Anthropic didn't write one, because it doesn't know Helpdesk exists, and you can't add Ruby methods to Claude Code.</p>
<p><strong>MCP is a standard way for an AI application like Claude Code to use tools that live in another program, like Helpdesk.</strong> Its docs describe it as &quot;an open-source standard for connecting AI applications to external systems,&quot; and compare it to a USB-C port for AI applications. The program that offers the tools is called an MCP server.</p>
<p>In this situation, the MCP server is our Helpdesk app, and we're the ones who build it. We'd add an endpoint to Helpdesk that speaks the protocol (it's JSON over HTTP, so a Rails controller can do it), with a <code>find_ticket</code> tool behind it. Then we'd add the endpoint's URL to Claude Code's settings:</p>
<pre data-language="text"><code class="code-inline language-text">Claude (the model)  &lt;-- Claude API --&gt;  Claude Code  &lt;-- MCP --&gt;  Helpdesk (Rails)
                                        AI application            MCP server
                                        runs the loop             runs find_ticket</code></pre>
<p>Here's what happens when you ask Claude Code about the ticket:</p>
<ol>
<li>When it starts, Claude Code connects to Helpdesk and sends a <code>tools/list</code> request. Helpdesk replies with its tools, each with a <code>name</code>, a <code>description</code>, and an <code>inputSchema</code>: the same three parts we wrote for <code>find_customer</code>.</li>
<li>Claude Code includes those definitions in the <code>tools</code> it sends to Claude, alongside its own tools for reading and editing files.</li>
<li>Claude replies with a <code>tool_use</code> block asking for <code>find_ticket</code>, exactly as it asked our sidebar for <code>find_customer</code>.</li>
<li>Claude Code doesn't have the code for <code>find_ticket</code>, so it sends a <code>tools/call</code> request to Helpdesk with the tool's name and input.</li>
<li>Helpdesk runs its Ruby code, scoped to what your login is allowed to see, and returns the ticket. Claude Code sends it back to Claude as a <code>tool_result</code>, and the loop continues.</li>
</ol>
<p><strong>The model never knows MCP is involved.</strong> Claude sees tool definitions and asks for tool calls, exactly as in the rest of this post. MCP is the connection between Claude Code that runs the loop and the program (Helpdesk) where a tool's code lives.</p>
<p><strong>Who builds MCP servers?</strong> Whoever owns the data or the actions. Sentry runs one so that Claude Code, or any other AI application, can look up errors in your Sentry account. Basecamp has one so you could work with your projects in Claude Code. GitHub runs one for repositories and pull requests. Helpdesk would run one for tickets.</p>
<p>So Helpdesk can play either role, depending on who's running the loop. In the sidebar, Helpdesk is the AI application. It runs the loop and its own tools, and it doesn't need MCP at all. When we want Claude Code, the Claude desktop app, or our customers' own AI tools to reach Helpdesk's data, Helpdesk is the MCP server. It could even be both: if we wanted the sidebar to look up errors in Sentry, Helpdesk could connect to Sentry's MCP server and pass Sentry's tools to Claude alongside <code>find_customer</code>. (The Claude API can do that connecting for you. Its MCP connector, in beta as of November 2026, is a server tool that connects to a remote MCP server on your behalf, the same way web search runs searches on your behalf.)</p>
<p>For a web developer, tool use is like calling a method in your own app. MCP is like publishing an API so that other people's apps (Claude Code) can call your code. (MCP has more in it than tools: servers can also expose resources and prompt templates. But tools are what most people mean when they talk about it.) If you're building AI features inside your own Rails app, you don't need MCP. You define tools and run them, the way we did here. MCP becomes useful when you want your app's data and actions available inside AI applications you don't control.</p>
<p>I will cover building an MCP server in Rails in a future post.</p>

</div>
]]></content:encoded><pubDate>Mon, 09 Nov 2026 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/claude-tool-use-explained</link><guid isPermaLink="true">https://writesoftwarewell.com/claude-tool-use-explained</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>My Understanding of How Large Language Models Work</title><description>Lately, I've been trying to learn more about AI, particularly large language models (LLMs). My usual approach to learning a new subject is to read the classic books on the topic. However, since this version of generative and agentic AI is so new and evolving so rapidly, it's been difficult to find good, established books that covers it and explains it so a web developer like me could understand it.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>Lately, I've been trying to learn more about AI, particularly large language models (LLMs). My usual approach to learning a new subject is to read the classic books on the topic. However, since this version of generative and agentic AI is so new and evolving so rapidly, it's been difficult to find good, established books that covers it and explains it so a web developer like me could understand it.</p>
<p>So I decided to try something different by <strong>learning AI with AI.</strong> That is, I asked Claude to explain how LLMs work over a series of back-and-forth conversations over a few days to build my understanding of the topic. This post is my attempt to explain what I've learned about how LLMs work.</p>
<p>I'm a web developer, not an AI or machine learning researcher, and I'm writing this from the perspective of a student learning a new subject, not an expert teaching it. In fact, one of my motivations for writing this post is to clarify my own understanding of LLMs. If you notice any mistakes or inaccuracies, please let me know. I hope you find it useful!</p>
<hr>
<p>A large language model (LLM) is a program that takes a piece of text and predicts what comes next. You give it some text, it gives you back a list of possible next pieces of text, each with a probability, and one of them gets picked. Then the picked piece is appended to the text and the whole thing runs again. Chatbots, coding agents, ticket classifiers, and everything else you've seen built on Claude or GPT are this one loop, run many times, with a lot of engineering around it.</p>
<p>You don't need to understand the math to build good AI features. But you do need an accurate mental model of what's going on, because almost every confusing thing a model does (making up facts, forgetting what you said two messages ago, answering the same question differently each time, miscounting letters in a word) follows directly from how it works. Once you see the mechanism, those behaviors stop being mysterious and start being things you can work around.</p>
<h2 id="the-one-thing-an-llm-does">The One Thing An LLM Does</h2>
<p>Imagine the text &quot;The customer could not log&quot; and ask yourself what word comes next. You'd probably say &quot;in&quot;. You might also say &quot;on&quot; or &quot;into&quot;. You almost certainly wouldn't say &quot;Rails&quot;. Without thinking about it, you assigned probabilities to possible next words based on everything you've read in your life.</p>
<p>An LLM does the same thing, explicitly. Given &quot;The customer could not log&quot;, it produces a probability for every piece of text it knows about. Something like:</p>
<pre data-language="text"><code class="code-inline language-text">&#34; in&#34;     0.91
&#34; on&#34;     0.05
&#34; into&#34;   0.03
...
&#34; Rails&#34; 0.0000001</code></pre>
<p>One of these gets chosen, say &quot; in&quot;, and appended to the input. Now the input is &quot;The customer could not log in&quot;, and the model runs again to predict the piece after that. This repeats until the model produces a special &quot;I'm done&quot; marker or hits a length limit you set.</p>
<p>This is what people mean when they call these models <a href="https://aws.amazon.com/what-is/autoregressive-models/">autoregressive</a>: each output is fed back in as input for the next step. It's also why responses stream in word by word in a chat interface. The model really is producing them one at a time, and the API is just sending each one to you as soon as it exists. As a result, the model never plans out an answer and then types it.</p>
<h4 id="tokens-not-words">Tokens, Not Words</h4>
<p>I've been saying &quot;piece of text&quot; instead of &quot;word&quot;, as models don't read words or characters. They read tokens.</p>
<p>A token is a chunk of text from a fixed vocabulary that the model was built with. Common words are usually a single token. Rarer words are split into several. OpenAI's docs describe a token as a commonly occurring sequence of characters, and give a rough rule of thumb for English: about 4 characters, or three quarters of a word, per token.</p>
<p>The exact split depends on the model. A token on older Claude models is about 3.5 English characters, and Claude Opus 4.7 and later use a newer tokenizer that produces about 30% more tokens for the same text. So the same paragraph costs a different number of tokens on different models, and you can't compare token counts across providers or even across model generations. When you need an exact number, both providers have token counting endpoints that will tell you, for the specific model you plan to use.</p>
<p>Before the model sees your text, a tokenizer converts it into a list of integers, one per token. The model only ever works with those integers. It never sees the letters.</p>
<p>Tokens are the unit of everything. You're billed per token, in and out. Context limits are measured in tokens. Speed is measured in tokens per second. When someone says a model is expensive, they mean its price per million tokens is high.</p>
<h2 id="a-next-word-predictor-in-ruby">A Next-Word Predictor In Ruby</h2>
<p>The best way I've found to understand next-token prediction is to build a very simple version of it. Here's a model that predicts the next word by counting which words followed which in some training text:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># A toy, for understanding only. Real models work very differently inside.</span>
<span class="k">class</span> <span class="nc">Bigram</span>
  <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">text</span><span class="p">)</span>
    <span class="vi">@counts</span> <span class="o">=</span> <span class="no">Hash</span><span class="o">.</span><span class="n">new</span> <span class="p">{</span> <span class="o">|</span><span class="nb">hash</span><span class="p">,</span> <span class="n">word</span><span class="o">|</span> <span class="nb">hash</span><span class="o">[</span><span class="n">word</span><span class="o">]</span> <span class="o">=</span> <span class="no">Hash</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="p">}</span>

    <span class="n">text</span><span class="o">.</span><span class="n">downcase</span><span class="o">.</span><span class="n">scan</span><span class="p">(</span><span class="sr">/[\w&#39;]+|[.,?!]/</span><span class="p">)</span><span class="o">.</span><span class="n">each_cons</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">word</span><span class="p">,</span> <span class="n">next_word</span><span class="o">|</span>
      <span class="vi">@counts</span><span class="o">[</span><span class="n">word</span><span class="o">][</span><span class="n">next_word</span><span class="o">]</span> <span class="o">+=</span> <span class="mi">1</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">probabilities</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
    <span class="n">followers</span> <span class="o">=</span> <span class="vi">@counts</span><span class="o">[</span><span class="n">word</span><span class="o">]</span>
    <span class="n">total</span> <span class="o">=</span> <span class="n">followers</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">sum</span><span class="o">.</span><span class="n">to_f</span>

    <span class="n">followers</span><span class="o">.</span><span class="n">transform_values</span> <span class="p">{</span> <span class="n">it</span> <span class="o">/</span> <span class="n">total</span> <span class="p">}</span><span class="o">.</span><span class="n">sort_by</span> <span class="p">{</span> <span class="o">-</span><span class="n">it</span><span class="o">.</span><span class="n">last</span> <span class="p">}</span><span class="o">.</span><span class="n">to_h</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This Ruby class implements a simple <strong>Bigram language model</strong>. In plain English, it reads some text, learns which words tend to follow other words, and calculates the probability of each possible next word.</p>
<p>First, we initialize a nested hash to keep track of how often each word follows another:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="vi">@counts</span> <span class="o">=</span> <span class="no">Hash</span><span class="o">.</span><span class="n">new</span> <span class="p">{</span> <span class="o">|</span><span class="nb">hash</span><span class="p">,</span> <span class="n">word</span><span class="o">|</span> <span class="nb">hash</span><span class="o">[</span><span class="n">word</span><span class="o">]</span> <span class="o">=</span> <span class="no">Hash</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="p">}</span></code></pre>
<p>The outer hash stores the current word, while the inner hash stores the words that follow it, along with their frequency. Using <code>Hash.new(0)</code> lets us increment the counts without having to initialize them first.</p>
<p>Next, we break the input text into individual words and punctuation marks:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">text</span><span class="o">.</span><span class="n">downcase</span><span class="o">.</span><span class="n">scan</span><span class="p">(</span><span class="sr">/[\w&#39;]+|[.,?!]/</span><span class="p">)</span></code></pre>
<p>We convert everything to lowercase so that <code>&quot;Ruby&quot;</code> and <code>&quot;ruby&quot;</code> are treated as the same word.</p>
<p>For example, <code>&quot;I love Ruby.&quot;</code> becomes:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="o">[</span><span class="s2">&#34;i&#34;</span><span class="p">,</span> <span class="s2">&#34;love&#34;</span><span class="p">,</span> <span class="s2">&#34;ruby&#34;</span><span class="p">,</span> <span class="s2">&#34;.&#34;</span><span class="o">]</span></code></pre>
<p>The <code>each_cons(2)</code> method iterates over consecutive pairs of words.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="o">.</span><span class="n">each_cons</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">word</span><span class="p">,</span> <span class="n">next_word</span><span class="o">|</span>
  <span class="vi">@counts</span><span class="o">[</span><span class="n">word</span><span class="o">][</span><span class="n">next_word</span><span class="o">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">end</span></code></pre>
<p>For our example, it produces:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="o">[</span><span class="s2">&#34;i&#34;</span><span class="p">,</span> <span class="s2">&#34;love&#34;</span><span class="o">]</span>
<span class="o">[</span><span class="s2">&#34;love&#34;</span><span class="p">,</span> <span class="s2">&#34;ruby&#34;</span><span class="o">]</span>
<span class="o">[</span><span class="s2">&#34;ruby&#34;</span><span class="p">,</span> <span class="s2">&#34;.&#34;</span><span class="o">]</span></code></pre>
<p>For each pair, we increment the count of how often the second word follows the first. That's essentially what a <strong>bigram</strong> is: a sequence of two consecutive words (or tokens).</p>
<p>Finally, the <code>probabilities</code> method calculates how likely each word is to follow a given word:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">probabilities</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
  <span class="n">followers</span> <span class="o">=</span> <span class="vi">@counts</span><span class="o">[</span><span class="n">word</span><span class="o">]</span>
  <span class="n">total</span> <span class="o">=</span> <span class="n">followers</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">sum</span><span class="o">.</span><span class="n">to_f</span>

  <span class="n">followers</span><span class="o">.</span><span class="n">transform_values</span> <span class="p">{</span> <span class="n">it</span> <span class="o">/</span> <span class="n">total</span> <span class="p">}</span><span class="o">.</span><span class="n">sort_by</span> <span class="p">{</span> <span class="o">-</span><span class="n">it</span><span class="o">.</span><span class="n">last</span> <span class="p">}</span><span class="o">.</span><span class="n">to_h</span>
<span class="k">end</span></code></pre>
<p>It retrieves all the words that followed the given word, adds up their occurrences, and divides each word's count by the total.</p>
<p>For example, suppose our input text is:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="s2">&#34;I love Ruby. I love Rails. I love programming.&#34;</span></code></pre>
<p>The word <code>&quot;love&quot;</code> is followed by <code>&quot;ruby&quot;</code>, <code>&quot;rails&quot;</code>, and <code>&quot;programming&quot;</code> exactly once each.</p>
<p>So calling:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">bigram</span><span class="o">.</span><span class="n">probabilities</span><span class="p">(</span><span class="s2">&#34;love&#34;</span><span class="p">)</span></code></pre>
<p>Returns approximately:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="p">{</span>
  <span class="s2">&#34;ruby&#34;</span> <span class="o">=&gt;</span> <span class="mi">0</span><span class="o">.</span><span class="mi">333</span><span class="p">,</span>
  <span class="s2">&#34;rails&#34;</span> <span class="o">=&gt;</span> <span class="mi">0</span><span class="o">.</span><span class="mi">333</span><span class="p">,</span>
  <span class="s2">&#34;programming&#34;</span> <span class="o">=&gt;</span> <span class="mi">0</span><span class="o">.</span><span class="mi">333</span>
<span class="p">}</span></code></pre>
<p>Each word has a 33.3% probability of following <code>&quot;love&quot;</code>, based on the input text. The results are sorted from highest to lowest probability. That's the model's prediction: given a word, here's how likely each possible next word is.</p>
<p>This is a simple language model that learns word patterns from text and uses them to predict what might come next.</p>
<p>Of course, this model only considers the immediate word before the target, without understanding the meaning or broader context of a sentence. But it shows the fundamental idea behind statistical language modeling: <strong>using patterns in existing text to predict the next word.</strong></p>
<p>Let's train it on a few sentences from a support inbox:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">corpus</span> <span class="o">=</span> <span class="o">&lt;&lt;~</span><span class="no">TEXT</span>
  <span class="no">The</span> <span class="n">customer</span> <span class="n">could</span> <span class="ow">not</span> <span class="n">log</span> <span class="k">in</span><span class="o">.</span> <span class="no">The</span> <span class="n">customer</span> <span class="n">reset</span> <span class="n">the</span> <span class="n">password</span><span class="o">.</span>
  <span class="no">The</span> <span class="n">agent</span> <span class="n">replied</span> <span class="n">to</span> <span class="n">the</span> <span class="n">customer</span><span class="o">.</span> <span class="no">The</span> <span class="n">agent</span> <span class="n">closed</span> <span class="n">the</span> <span class="n">ticket</span><span class="o">.</span>
  <span class="no">The</span> <span class="n">ticket</span> <span class="n">was</span> <span class="n">about</span> <span class="n">billing</span><span class="o">.</span> <span class="no">The</span> <span class="n">customer</span> <span class="n">was</span> <span class="n">happy</span> <span class="n">with</span> <span class="n">the</span> <span class="n">reply</span><span class="o">.</span>
<span class="no">TEXT</span>

<span class="n">model</span> <span class="o">=</span> <span class="no">Bigram</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">corpus</span><span class="p">)</span>
<span class="n">model</span><span class="o">.</span><span class="n">probabilities</span><span class="p">(</span><span class="s2">&#34;the&#34;</span><span class="p">)</span>
<span class="c1"># =&gt; {&#34;customer&#34; =&gt; 0.4, &#34;agent&#34; =&gt; 0.2, &#34;ticket&#34; =&gt; 0.2, &#34;password&#34; =&gt; 0.1, &#34;reply&#34; =&gt; 0.1}</span></code></pre>
<p>&quot;The&quot; was followed by &quot;customer&quot; 4 times out of 10, so the model says there's a 40% chance the next word is &quot;customer&quot;. That's the model, and it really is a language model, just a tiny and dumb one.</p>
<p>Now we need a way to generate text with it. The obvious approach is to always pick the most likely word:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">Bigram</span>
  <span class="k">def</span> <span class="nf">generate</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="ss">length</span><span class="p">:</span> <span class="mi">12</span><span class="p">)</span>
    <span class="n">words</span> <span class="o">=</span> <span class="o">[</span> <span class="n">word</span> <span class="o">]</span>

    <span class="n">length</span><span class="o">.</span><span class="n">times</span> <span class="k">do</span>
      <span class="n">candidates</span> <span class="o">=</span> <span class="n">probabilities</span><span class="p">(</span><span class="n">words</span><span class="o">.</span><span class="n">last</span><span class="p">)</span>
      <span class="k">break</span> <span class="k">if</span> <span class="n">candidates</span><span class="o">.</span><span class="n">empty?</span>

      <span class="n">words</span> <span class="o">&lt;&lt;</span> <span class="n">candidates</span><span class="o">.</span><span class="n">keys</span><span class="o">.</span><span class="n">first</span>
    <span class="k">end</span>

    <span class="n">words</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s2">&#34; &#34;</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="n">model</span><span class="o">.</span><span class="n">generate</span><span class="p">(</span><span class="s2">&#34;the&#34;</span><span class="p">)</span>
<span class="c1"># =&gt; &#34;the customer could not log in . the customer could not log in&#34;</span></code></pre>
<p>This is the autoregressive loop. It also shows our first problem. Always taking the top choice gets the model stuck in a loop, repeating the most probable path forever. The fix is to pick randomly, weighted by probability, so that &quot;customer&quot; is picked 40% of the time and &quot;password&quot; 10% of the time:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">Bigram</span>
  <span class="k">def</span> <span class="nf">generate</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="ss">length</span><span class="p">:</span> <span class="mi">12</span><span class="p">)</span>
    <span class="n">words</span> <span class="o">=</span> <span class="o">[</span> <span class="n">word</span> <span class="o">]</span>

    <span class="n">length</span><span class="o">.</span><span class="n">times</span> <span class="k">do</span>
      <span class="n">candidates</span> <span class="o">=</span> <span class="n">probabilities</span><span class="p">(</span><span class="n">words</span><span class="o">.</span><span class="n">last</span><span class="p">)</span>
      <span class="k">break</span> <span class="k">if</span> <span class="n">candidates</span><span class="o">.</span><span class="n">empty?</span>

      <span class="n">words</span> <span class="o">&lt;&lt;</span> <span class="n">sample</span><span class="p">(</span><span class="n">candidates</span><span class="p">)</span>
    <span class="k">end</span>

    <span class="n">words</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s2">&#34; &#34;</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="kp">private</span>
    <span class="k">def</span> <span class="nf">sample</span><span class="p">(</span><span class="n">candidates</span><span class="p">)</span>
      <span class="n">roll</span> <span class="o">=</span> <span class="nb">rand</span>

      <span class="n">candidates</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">word</span><span class="p">,</span> <span class="n">probability</span><span class="o">|</span>
        <span class="n">roll</span> <span class="o">-=</span> <span class="n">probability</span>
        <span class="k">return</span> <span class="n">word</span> <span class="k">if</span> <span class="n">roll</span> <span class="o">&lt;=</span> <span class="mi">0</span>
      <span class="k">end</span>

      <span class="n">candidates</span><span class="o">.</span><span class="n">keys</span><span class="o">.</span><span class="n">last</span>
    <span class="k">end</span>
<span class="k">end</span></code></pre>
<p><code>sample</code> rolls a random number between 0 and 1 and walks through the candidates, subtracting each probability until the roll runs out. A word with probability 0.4 covers 40% of the range, so it's chosen 40% of the time. (The last line is there in case floating-point rounding leaves a tiny remainder.)</p>
<p>Running it three times gives three different outputs:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">the</span> <span class="n">customer</span> <span class="n">reset</span> <span class="n">the</span> <span class="n">password</span> <span class="o">.</span> <span class="n">the</span> <span class="n">ticket</span> <span class="o">.</span> <span class="n">the</span> <span class="n">agent</span> <span class="n">replied</span> <span class="n">to</span>
<span class="n">the</span> <span class="n">customer</span> <span class="n">was</span> <span class="n">happy</span> <span class="n">with</span> <span class="n">the</span> <span class="n">agent</span> <span class="n">replied</span> <span class="n">to</span> <span class="n">the</span> <span class="n">reply</span> <span class="o">.</span> <span class="n">the</span>
<span class="n">the</span> <span class="n">ticket</span> <span class="n">was</span> <span class="n">about</span> <span class="n">billing</span> <span class="o">.</span> <span class="n">the</span> <span class="n">agent</span> <span class="n">closed</span> <span class="n">the</span> <span class="n">ticket</span> <span class="o">.</span> <span class="n">the</span></code></pre>
<p>We used the same model and the same input, however got a different text. Because it's exactly why a real LLM gives you a different answer each time you ask.</p>
<p>You can also see what's fundamentally wrong with this model. It only looks at one word back. &quot;The agent replied to the reply&quot; is a perfectly probable sequence of word pairs and complete nonsense as a sentence. To write sensibly, a model needs to consider the whole text, not just the last word. If the text is about a customer who can't log in, &quot;password&quot; should become far more likely than &quot;billing&quot;, even if &quot;password&quot; is many words back.</p>
<h2 id="what-a-real-llm-does-differently">What A Real LLM Does Differently</h2>
<p>A real LLM keeps the same contract as our toy (text in, probabilities for the next token out), but differs in three big ways.</p>
<p><strong>First, it looks at everything.</strong> When it predicts the next token, it takes the entire input into account, every token from the beginning of the conversation. The architecture that makes this possible is called the transformer, and its key idea, attention, lets the model decide for each position which earlier tokens are relevant. When predicting what comes after &quot;Can you reset my&quot;, attention lets the model pick up on &quot;log in&quot; from three sentences ago, which pushes &quot;password&quot; up. You don't need to know how attention works to build AI features. It's enough to know that the model weighs the whole context, and that the amount of context it can handle at once is limited.</p>
<p><strong>Second, it doesn't store counts.</strong> Our toy model memorizes a table of word pairs. An LLM instead consists of billions of numbers called parameters (or weights). There's no table to look up, and no place inside where a particular fact is written down. Your input tokens are converted into numbers and pushed through layer after layer of arithmetic using those parameters, and out the other end comes a probability for every token in the vocabulary. Whatever the model &quot;knows&quot; is spread across all of those numbers.</p>
<p><strong>Third, it generalizes.</strong> Because it isn't looking up exact sequences, a large model can handle text it has never seen before. Our bigram model has nothing to say about &quot;the invoice&quot;, because it never saw &quot;invoice&quot;. An LLM has seen enough text to have learned that invoices are related to billing, that people who can't log in often want password resets, and an enormous amount of other structure about language and the world.</p>
<p>That leaves the obvious question. If nobody writes those billions of parameters by hand, where do they come from?</p>
<h2 id="where-the-probabilities-come-from-training">Where The Probabilities Come From: Training</h2>
<p>Language models like Claude aren't programmed directly by humans, they're trained on large amounts of data. Training happens in stages.</p>
<p><strong>The first stage is pretraining.</strong> The model starts with random parameters, so its predictions are garbage. It's then shown a huge amount of text (a large part of the public internet, books, code, and more) and, for each position in that text, asked to predict the next token. Since the real next token is right there in the text, it's easy to check how wrong the prediction was. The parameters are then nudged slightly in the direction that would have made the correct token more likely. Repeat that trillions of times and the predictions get very good.</p>
<p>There's no labeling and no human telling the model what's true. The text itself provides the answers. And it turns out that to predict the next token in a physics textbook, a Ruby file, or a legal contract really well, a model has to pick up a lot of physics, Ruby, and law along the way.</p>
<p>What you get at the end of pretraining is called a base model, and it's surprisingly unhelpful. Anthropic's says that pretrained models &quot;are not inherently good at answering questions or following instructions.&quot; A base model completes documents. Give it &quot;What is the capital of France?&quot; and it might continue with &quot;What is the capital of Germany? What is the capital of Spain?&quot;, because in its training data, a question like that is often part of a quiz. It's predicting what document this is likely to be, not trying to help you.</p>
<h3 id="turning-a-base-model-into-an-assistant">Turning A Base Model Into An Assistant</h3>
<p><strong>The second stage turns the document completer into an assistant.</strong> There are a few techniques, and providers combine them.</p>
<p>Fine-tuning means continuing to train the model, but on a smaller, carefully chosen dataset. If you train it on thousands of example conversations where a user asks something and an assistant answers helpfully, the model learns that pattern. Now when it sees a question, the most likely continuation is a helpful answer.</p>
<p>Reinforcement learning from human feedback (RLHF) goes further. The model generates several responses to the same prompt, people rank them from best to worst, and training pushes the model toward responses like the higher-ranked ones. This is how models learn the fuzzier qualities that are hard to show with examples alone, like being concise, admitting uncertainty, or declining harmful requests.</p>
<p>Newer models also go through reinforcement learning on tasks where the result can be checked automatically, like math problems with known answers or code that has to pass tests. This is a big part of how reasoning models learned to work through problems step by step, which we'll come back to.</p>
<h2 id="choosing-the-next-token-sampling">Choosing The Next Token: Sampling</h2>
<p>Back to our toy model's <code>sample</code> method. Real models face the same choice we did. Always taking the most likely token tends to produce repetitive, flat text. Sampling randomly by probability produces more natural text but less predictable results.</p>
<p>Historically, APIs exposed a parameter called <a href="https://academy.claude.com/courses/building-with-the-claude-api/temperature">temperature</a> to control this. A low temperature sharpens the probabilities so the top choices win almost every time. A high temperature flattens them so less likely tokens get picked more often. Anthropic's glossary describes lower temperatures as producing &quot;more conservative and deterministic outputs&quot; and higher ones as encouraging &quot;rare, uncommon, or surprising word choices.&quot;</p>
<p>There are two things worth knowing about temperature in practice. Even at temperature 0, results aren't fully deterministic. Identical inputs can produce different outputs across API calls. Small numerical differences in how the calculation runs on the provider's hardware can tip a close call between two tokens, and once one token differs, everything after it can differ too.</p>
<p>The second is that, as of November 2026, the current Claude models don't accept temperature at all. Sending <code>temperature</code>, <code>top_p</code>, or <code>top_k</code> to Claude Opus 4.7 or later returns an error, and the docs recommend steering behavior through the prompt instead. If you're reading older tutorials that set <code>temperature: 0</code> to get consistent output, that advice doesn't carry over.</p>
<p>So you should design every AI feature assuming the output will vary. That's why you can't test an LLM feature the way you test a method that returns a fixed value, and why evals (tests that score many outputs instead of asserting one) exist.</p>
<h2 id="the-model-remembers-nothing">The Model Remembers Nothing</h2>
<p>HTTP is a stateless protocol. The server doesn't remember you between requests, so <a href="https://writesoftwarewell.com/rails-sessions">your browser sends a session cookie every time</a>, and Rails uses it to rebuild who you are.</p>
<p>LLM APIs work the same way. The model has no memory between calls. The Messages API from the model providers is is stateless, which means that you always send the full conversational history to the API. Each text generation request is independent and stateless.</p>
<p>When you chat with Claude and it seems to remember your name from five messages ago, that's because the app sent all five messages again, along with your new one. Here's what that looks like at the HTTP level:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="nb">require</span> <span class="s2">&#34;net/http&#34;</span>
<span class="nb">require</span> <span class="s2">&#34;json&#34;</span>

<span class="k">def</span> <span class="nf">ask</span><span class="p">(</span><span class="n">messages</span><span class="p">)</span>
  <span class="n">uri</span> <span class="o">=</span> <span class="no">URI</span><span class="p">(</span><span class="s2">&#34;https://api.anthropic.com/v1/messages&#34;</span><span class="p">)</span>

  <span class="n">request</span> <span class="o">=</span> <span class="no">Net</span><span class="o">::</span><span class="no">HTTP</span><span class="o">::</span><span class="no">Post</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
  <span class="n">request</span><span class="o">[</span><span class="s2">&#34;x-api-key&#34;</span><span class="o">]</span> <span class="o">=</span> <span class="no">ENV</span><span class="o">.</span><span class="n">fetch</span><span class="p">(</span><span class="s2">&#34;ANTHROPIC_API_KEY&#34;</span><span class="p">)</span>
  <span class="n">request</span><span class="o">[</span><span class="s2">&#34;anthropic-version&#34;</span><span class="o">]</span> <span class="o">=</span> <span class="s2">&#34;2026-10-21&#34;</span>
  <span class="n">request</span><span class="o">[</span><span class="s2">&#34;content-type&#34;</span><span class="o">]</span> <span class="o">=</span> <span class="s2">&#34;application/json&#34;</span>
  <span class="n">request</span><span class="o">.</span><span class="n">body</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">model</span><span class="p">:</span> <span class="s2">&#34;claude-sonnet-5-5&#34;</span><span class="p">,</span> <span class="ss">max_tokens</span><span class="p">:</span> <span class="mi">1024</span><span class="p">,</span> <span class="ss">messages</span><span class="p">:</span> <span class="n">messages</span> <span class="p">}</span><span class="o">.</span><span class="n">to_json</span>

  <span class="n">response</span> <span class="o">=</span> <span class="no">Net</span><span class="o">::</span><span class="no">HTTP</span><span class="o">.</span><span class="n">start</span><span class="p">(</span><span class="n">uri</span><span class="o">.</span><span class="n">host</span><span class="p">,</span> <span class="n">uri</span><span class="o">.</span><span class="n">port</span><span class="p">,</span> <span class="ss">use_ssl</span><span class="p">:</span> <span class="kp">true</span><span class="p">)</span> <span class="p">{</span> <span class="n">it</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="p">}</span>
  <span class="no">JSON</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">body</span><span class="p">)</span>
<span class="k">end</span>

<span class="n">messages</span> <span class="o">=</span> <span class="o">[</span> <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="s2">&#34;Hi, I&#39;m John. I can&#39;t log in to my account.&#34;</span> <span class="p">}</span> <span class="o">]</span>
<span class="n">reply</span> <span class="o">=</span> <span class="n">ask</span><span class="p">(</span><span class="n">messages</span><span class="p">)</span>

<span class="n">messages</span> <span class="o">&lt;&lt;</span> <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;assistant&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="n">reply</span><span class="o">[</span><span class="s2">&#34;content&#34;</span><span class="o">].</span><span class="n">find</span> <span class="p">{</span> <span class="n">it</span><span class="o">[</span><span class="s2">&#34;type&#34;</span><span class="o">]</span> <span class="o">==</span> <span class="s2">&#34;text&#34;</span> <span class="p">}</span><span class="o">[</span><span class="s2">&#34;text&#34;</span><span class="o">]</span> <span class="p">}</span>
<span class="n">messages</span> <span class="o">&lt;&lt;</span> <span class="p">{</span> <span class="ss">role</span><span class="p">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="ss">content</span><span class="p">:</span> <span class="s2">&#34;What was my name again?&#34;</span> <span class="p">}</span>

<span class="n">ask</span><span class="p">(</span><span class="n">messages</span><span class="p">)</span></code></pre>
<p>The <code>ask</code> method sends a single POST request with the model, a maximum number of output tokens, and a list of messages. Each message has a role: <code>user</code> for what the person said and <code>assistant</code> for what the model said.</p>
<p>To continue the conversation, we append the model's reply to <code>messages</code> as an assistant message, then append the new user message, and send the whole array again. The second request contains John's name only because we put it there. If you sent <code>[{ role: &quot;user&quot;, content: &quot;What was my name again?&quot; }]</code> alone, the model would have no idea.</p>
<p>(The <code>find</code> is there because the response's <code>content</code> is an array of blocks, and on models that think before answering, the first block can be the model's reasoning rather than its reply.)</p>
<p>The model's reply also comes with a <code>usage</code> field reporting how many tokens went in and how many came out. Watch the input count grow as the conversation gets longer, because it changes how you think about cost.</p>
<h3 id="the-context-window">The Context Window</h3>
<p>Everything you send in a request, plus everything the model generates in response, has to fit in the model's context window. Think of it as the model's &quot;working memory&quot;, distinct from the huge dataset it was trained on. The system prompt, every message, any documents or images, tool definitions, and the output all count toward it.</p>
<p>As of November 2026, the current Claude models have a 1M-token context window, which Anthropic estimates at roughly 555,000 English words on the current tokenizer. That sounds like plenty, and for a single request it usually is. But there are two things to keep in mind.</p>
<p>The first is cost. Because you resend the whole conversation each turn, the input grows with every message. Say each turn adds 500 tokens. By turn 40, a single request sends 20,000 input tokens, and the total input across all 40 turns is about 410,000 tokens. On Claude Sonnet 5.5 at $2 per million input tokens (as of November 2026), that's about 82 cents for one conversation. That's fine for one user, and adds up for thousands. Long conversations get expensive in a way that short ones don't hint at.</p>
<p>The second is quality. Anthropic's docs say that &quot;more context isn't automatically better. As token count grows, accuracy and recall degrade, a phenomenon known as context rot.&quot; A model given 500 pages and asked about one sentence is more likely to miss it than a model given the right two pages. Choosing what goes into the context is one of the main skills of building AI features, and a lot of the techniques you'll hear about (summarizing old messages, retrieval, compaction) exist to keep the context small and relevant.</p>
<h2 id="what-the-model-knows-and-what-it-makes-up">What The Model Knows, And What It Makes Up</h2>
<p>Everything a model knows from training was frozen when training ended. Anthropic lists a &quot;reliable knowledge cutoff&quot; for each model, the date through which its knowledge is most reliable. For the current Claude models, that's June 2026 (as of November 2026). The model doesn't know about anything after that unless you tell it.</p>
<p><strong>More importantly for your app, the model has never seen your data.</strong> It doesn't know your customers, your tickets, your pricing, or your refund policy. The only way it can use that information is if you put it in the request. When people talk about retrieval-augmented generation (RAG), they mean: find the relevant records in your database and include them in the prompt, so the model reads them in its context window instead of relying on what it memorized.</p>
<p>What happens when the model doesn't know something? Ideally, it says so. Sometimes it confidently makes something up instead. This is called hallucination, and if you've followed along, you can probably guess part of the reason. The model is trained to produce a probable continuation. A plausible-sounding wrong answer can be a very probable continuation.</p>
<p>For your application's AI features, the practical answer is the same one RAG gives: <strong>don't ask the model to recall specific facts. Give it the facts and ask it to work with them.</strong>&quot;Here's the customer's order history; is this order eligible for a refund under this policy?&quot; is a much safer question than &quot;What's our refund policy?&quot;</p>
<h3 id="thinking-models">Thinking Models</h3>
<p>There's one more piece that connects back to the autoregressive loop. Since each token is computed from the tokens before it, a model that writes out intermediate steps before the final answer gives itself more to work with. Writing &quot;36 + 59: 6 + 9 is 15, carry the 1...&quot; puts those steps into the context, where they can inform the following tokens.</p>
<p>That's what thinking (or reasoning) models do. Before answering, they generate a stream of reasoning tokens, trained through the reinforcement learning I mentioned earlier to be useful for getting the final answer right. In the Claude API, this shows up as thinking blocks in the response. As of November 2026, the current Claude models use adaptive thinking, where the model decides how much to think based on the problem and an effort setting you control.</p>
<p>Thinking isn't free. Thinking tokens are billed as output tokens and they take time to generate, so a model that thinks for a while before answering is both slower and more expensive. For a hard question, it's worth it. For classifying a ticket as billing or technical, it usually isn't.</p>
<h2 id="what-this-means-for-a-rails-app">What This Means For a Rails App</h2>
<p>Let me pull this together into what it changes about how you build things.</p>
<p>An LLM call is an HTTP request to a slow, metered, nondeterministic function. A response can take anywhere from under a second to a minute or more, depending on how many tokens are generated. That alone means <strong>model calls belong in background jobs, not in the request cycle, with results streamed or broadcast back to the page.</strong></p>
<p><strong>The model knows nothing about your app, so the quality of a feature depends mostly on what you put in the context.</strong> Most of the real work in AI features is the Rails work of gathering the right records, formatting them well, and keeping out what doesn't belong (including data the current user shouldn't see).</p>
<p><strong>Output varies and can be wrong, so you treat it like user input. Validate it, parse it into structured objects when you need structure, and keep a human in the loop</strong> when mistakes are costly. Test the parts you control, like the prompt you build, with ordinary unit tests, and use evals for the parts you don't.</p>

</div>
]]></content:encoded><pubDate>Thu, 05 Nov 2026 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/how-large-language-models-llms-work</link><guid isPermaLink="true">https://writesoftwarewell.com/how-large-language-models-llms-work</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Going Enterprise</title><description>For the past two years, I've been working with a client, an enterprise software company, and it has opened up a whole new world for me. There's so much I didn't know, and so much that can be made better. So going forward, enterprise software is what I'll be learning and writing about.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>For the past two years, I've been working with a client, an enterprise software company (built with Ruby on Rails, of course), particularly in the niche of software used by enterprises of all sizes + MSPs and IT administrators for real businesses like law firms, municipalities, architects, hospitals, manufacturers, financial institutions, and government agencies.</p>
<p>Working with an enterprise software company has revealed a whole new world of B2B software companies and managed service providers (MSPs) that I had no idea existed before. I guess most people building typical SaaS startups and Rails apps don’t know much about it either. Personally, I’ve had to revisit many of my priors about how a software business works.</p>
<p>So many things work differently in the enterprise world: how the software is developed, how it is marketed and sold, how it is licensed, how it is deployed, and how customers are supported (support is a huge, non-negotiable part of enterprise software, something I learned after handling a ton of support requests lately).</p>
<p>Take authentication, for example. Beyond email and password, there’s SAML, SSO, identity providers, and multi-factor authentication. Then there are the related concerns of SCIM provisioning and role-based access control, along with all the complexity of making these work with an enterprise’s existing systems.</p>
<p>And authentication is just one part of it. Audit logs, backwards compatibility, documentation, support, data retention, and encryption all demand your attention when building for enterprises. So do service-level agreements, disaster recovery, observability, compliance, configuration and customization. Then there’s the work of deploying on-premises, navigating security reviews and vendor assessments, and dealing with licensing and procurement processes.</p>
<p>These products are also not sold directly to the end users of the software. They involve IT administrators, security teams, procurement departments, legal teams, compliance officers, 3rd party software vendors, company executives, and a bunch of other roles you wouldn't come across in B2C or consumer software.</p>
<p>I seriously wish the mainstream software development discourse included these topics as much as growth, raising funding, product-led growth, freemium, going viral, building in public, becoming an indie hacker, or whatever the current SaaS trend happens to be. I also wish universities, colleges, and programming curriculum taught about this side of the industry.</p>
<p>Anyways, the more I work on the enterprise software, the more I'm enjoying working on it. It’s not as visible or fashionable as the typical SaaS apps, but that’s part of what makes it interesting and fun for me. There is a ton I don’t know, which also means there is plenty to explore, learn, and write about.</p>
<p>I also think this industry is very much immune from AI disruption, as the customers (which are real businesses and not developers) are just not interested in building, maintaining, hosting, securing, and debugging their own solution with AI. Here's a <a href="https://x.com/JackEllis/status/2109978565840130062">tweet</a> from Jack that perfectly summarizes this, except the fact that enterprise customers are not paying $15/month, they're often paying hundreds, thousands, or even hundreds of thousands of dollars and perfectly fine with it.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/iem6o0o76rneh1zm6gniugvmtkfl.png" alt="jack-ellis-tweet.png" loading="lazy">
  <figcaption class="attachment__caption">Jack Ellis Tweet</figcaption>
</figure><p>On the other hand, with all the power of AI agents we now have, I think there’s a lot of room to speed up all areas surrounding enterprise businesses. Plenty of businesses have software they want to improve and a long list of things they’ve learned to live with. They could use someone who can understand their business, help decide what’s worth fixing, and follow through.</p>
<p>That’s the work I want to do more of.</p>
<h3 id="everything-can-be-better-quickly">Everything can be better, quickly</h3>
<p>A few days ago, Jason Fried <a href="https://x.com/jasonfried/status/2109737418593321123">tweeted</a>:</p>
<blockquote>
<p>&quot;Building new stuff and improving existing stuff has never been more fun! EVERYTHING can be better quickly, but it's still a secret, plenty have no idea, and even those who do need a lot of help and direction to see what needs to be improved.&quot;</p>
<p>&quot;I love to fix. I love to make stuff easier on people. I love to show people a better way. I love to blow away the fog. I love to untangle.&quot;</p>
</blockquote>
<p>That describes exactly how I feel about enterprise software right now.</p>
<p>Enterprise software is where you find the most tangles. Products have been running for ten, twenty, sometimes thirty-plus years. The software works and real businesses depend on it every day, but it's often slow to change, hard to work on, and painful for the people using it. That's also where the opportunity is biggest. With modern tools (and yes, I mean AI agents), we can now improve existing software faster than ever.</p>
<p>Going forward, I want to go deep on the topics surrounding enterprise software: MSPs, SSO/SAML authentication, licensing, support, deployment, and the technologies and business models behind enterprise products. In short, anything and everything that touches the enterprise. The goal is to understand this largely invisible world deeply, and then use that understanding to make enterprise software better, using the powerful AI agents we have at our disposal.</p>
<p>In a way, this feels like coming home to me, as I started my career in a 35-year old enterprise software company (CityView) running on .NET that built and sold municipal software to local municipalities all over North America. I don’t think I fully appreciated that world at the time.</p>
<p>So enough about writing Ruby on Rails tutorials on the Write Software, Well blog. The agents are perfectly capable to explain all your programming questions. Enterprise software technology + business is what I will be learning and talking about going forward.</p>
<p>If you’re building, buying, selling, or supporting software in this world of enterprise software or managed services, I would love to connect with you.</p>
<p>Stay tuned!</p>

</div>
]]></content:encoded><pubDate>Tue, 13 Oct 2026 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/going-enterprise</link><guid isPermaLink="true">https://writesoftwarewell.com/going-enterprise</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>How to Safely Drop Columns in Rails</title><description>Dropping a column is simple in syntax but risky in production. Between running the migration and restarting the app, the old process still serves traffic with a cached schema, and can cause errors in production. Rails' ignored_columns fixes this by telling ActiveRecord to stop using a column before you actually drop it.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>Dropping a column from a database table is one of the simplest possible migrations, if you just look at the syntax. But if you run that migration in a large application used by a ton of users where taking the application down for maintenance is not an option, you may run into problems.</p>
<p>One thing I didn't realize until researching this post: ActiveRecord caches each model's schema the first time the model is loaded, and in production, with eager loading on, that means the whole schema is effectively cached at boot.</p>
<p>This matters because of the deploy order. The migration runs first, then the app server restarts onto the new schema. In between, there's a window where the old process is still serving traffic with its cached view of the schema. If a request comes in during that window and the migration dropped a column, the running app will try to <code>SELECT</code> or <code>INSERT</code> a column that no longer exists and you get errors in production.</p>
<p>Rails provides a mechanism to handle this cleanly: <code>ignored_columns</code>. Let's learn what problem it solves and how it works. We'll also look at some techniques to use for safely dropping important columns in heavily trafficked, critical databases. I didn't come up with them, these are just industry-wide best practices and you can learn more about them by reading this book: <a href="https://writesoftwarewell.com/refactoring-databases-in-rails">Refactoring Databases</a></p>
<h3 id="problem-with-dropping-columns-directly">Problem with dropping columns directly</h3>
<p>Consider a <code>projects</code> table with a <code>category</code> column you no longer need. The naive approach is to write a migration and deploy it.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">DropCategoryFromProjects</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">remove_column</span> <span class="ss">:projects</span><span class="p">,</span> <span class="ss">:category</span><span class="p">,</span> <span class="ss">:string</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This works fine if your deployment process restarts the application and runs migrations atomically, with no traffic hitting the app in between. But most production deployments don't work that way. In a typical setup, the migration runs first, the column is removed from the database, and then the application code is restarted. During that gap, the old application code is still running with a cached schema that includes <code>category</code>. Every query that touches the <code>projects</code> table, whether it explicitly references <code>category</code> or not, can break.</p>
<p>The exact error depends on how ActiveRecord builds its queries. If you're doing <code>Project.create!(name: &quot;foo&quot;)</code>, ActiveRecord might generate an INSERT that includes every column it knows about, setting unspecified ones to their defaults. The database will reject the query because the column no longer exists. SELECT queries using <code>*</code> will also return a different number of columns than ActiveRecord expects, causing attribute mapping errors.</p>
<p>Even if the deployment is fast and the window is small, it is not zero and under load, that window is more than enough time for requests to fail.</p>
<p>The fix is to tell ActiveRecord to stop using the column before you drop it. That's what <code>ignored_columns</code> does.</p>
<h3 id="how-ignored_columns-solves-this">How ignored_columns solves this</h3>
<p>First, you add the column that you want to drop to an ignored columns list, as follows.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">Project</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">ignored_columns</span> <span class="o">+=</span> <span class="o">[</span><span class="s2">&#34;category&#34;</span><span class="o">]</span>
<span class="k">end</span></code></pre>
<p>Once a column is in <code>ignored_columns</code>, ActiveRecord pretends it doesn't exist. It won't appear in <code>columns_hash</code>, won't have an attribute accessor, and won't be included in any generated SQL. The column is still in the database, but the application no longer knows about it.</p>
<p>This turns a risky one-step operation into a safe two-step process:</p>
<p><strong>Step 1:</strong> Add the column to <code>ignored_columns</code> and deploy the application. At this point, the column still exists in the database, but no code references it. You can verify this by running your test suite. If anything was still using the column, you'll get <code>NoMethodError</code> or query failures in your tests rather than in production.</p>
<p><strong>Step 2:</strong> After the first deploy is fully rolled out and stable, write and deploy the migration to actually drop the column.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">DropCategoryFromProjects</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">remove_column</span> <span class="ss">:projects</span><span class="p">,</span> <span class="ss">:category</span><span class="p">,</span> <span class="ss">:string</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Because the application is already ignoring the column, the migration can run without causing any errors. There's no dangerous window. The application doesn't care whether the column exists or not, because it stopped looking for it in the previous deploy.</p>
<h3 id="how-it-works">How it works</h3>
<p>The implementation is worth understanding, because it shows how ActiveRecord's schema caching works and why the timing problem exists in the first place.</p>
<p>When you set <code>ignored_columns</code> on a model, the setter does three things:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># activerecord/lib/active_record/model_schema.rb</span>
<span class="k">def</span> <span class="nf">ignored_columns</span><span class="o">=</span><span class="p">(</span><span class="n">columns</span><span class="p">)</span>
  <span class="n">check_model_columns</span><span class="p">(</span><span class="vi">@only_columns</span><span class="o">.</span><span class="n">present?</span><span class="p">)</span>
  <span class="n">reload_schema_from_cache</span>
  <span class="vi">@ignored_columns</span> <span class="o">=</span> <span class="n">columns</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:to_s</span><span class="p">)</span><span class="o">.</span><span class="n">freeze</span>
<span class="k">end</span></code></pre>
<p>First, it checks that you're not also using <code>only_columns</code> (a newer addition that takes the opposite approach: you specify the columns you want instead of the ones you don't). <strong>You can't use both.</strong></p>
<p>Second, it calls <code>reload_schema_from_cache</code>, which clears all the cached column data: <code>@columns_hash</code>, <code>@columns</code>, <code>@column_names</code>, <code>@attributes_builder</code>, and several other cached values. It also sets <code>@schema_loaded = false</code> and recursively invalidates all subclasses.</p>
<p>Third, it stores the ignored column names as frozen strings.</p>
<p>The filtering itself happens in <code>load_schema!</code>, which runs the next time anything accesses the model's column information:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">load_schema!</span>
  <span class="n">columns_hash</span> <span class="o">=</span> <span class="n">schema_cache</span><span class="o">.</span><span class="n">columns_hash</span><span class="p">(</span><span class="n">table_name</span><span class="p">)</span>
<span class="err">​</span>
  <span class="k">if</span> <span class="n">only_columns</span><span class="o">.</span><span class="n">present?</span>
    <span class="n">columns_hash</span> <span class="o">=</span> <span class="n">columns_hash</span><span class="o">.</span><span class="n">slice</span><span class="p">(</span><span class="o">*</span><span class="n">only_columns</span><span class="p">)</span>
  <span class="k">elsif</span> <span class="n">ignored_columns</span><span class="o">.</span><span class="n">present?</span>
    <span class="n">columns_hash</span> <span class="o">=</span> <span class="n">columns_hash</span><span class="o">.</span><span class="n">except</span><span class="p">(</span><span class="o">*</span><span class="n">ignored_columns</span><span class="p">)</span>
  <span class="k">end</span>
<span class="err">​</span>
  <span class="vi">@columns_hash</span> <span class="o">=</span> <span class="n">columns_hash</span><span class="o">.</span><span class="n">freeze</span>
<span class="k">end</span></code></pre>
<p>The model fetches the full column hash from the schema cache (which reflects the actual database schema), then removes the ignored columns using <code>Hash#except</code>. The filtered result is frozen and cached. From this point on, every method that depends on <code>columns_hash</code> (which is most of ActiveRecord's column-related API) works with the filtered set. <code>columns</code>, <code>column_names</code>, <code>attribute_names</code>, the attributes builder, all of them derive from this filtered hash.</p>
<p>The inheritance behavior is also worth noting. When a subclass is created, its <code>@ignored_columns</code> is set to <code>nil</code>, which means the getter falls through to the superclass:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">ignored_columns</span>
  <span class="vi">@ignored_columns</span> <span class="o">||</span> <span class="n">superclass</span><span class="o">.</span><span class="n">ignored_columns</span>
<span class="k">end</span></code></pre>
<p>So if you set <code>ignored_columns</code> on <code>ApplicationRecord</code>, every model in your app inherits it. If you set it on a specific model, only that model and its STI subclasses are affected.</p>
<h2 id="when-the-column-holds-critical-data">When the column holds critical data</h2>
<p>The two-step process above assumes you're dropping a column you don't need anymore. When the column contains data that needs to go somewhere else, the process gets a few more steps, but <code>ignored_columns</code> still plays the same role.</p>
<p>Say you're extracting a <code>phone_number</code> column from <code>users</code> into a separate <code>phone_numbers</code> table because users can now have multiple phone numbers.</p>
<p><strong>Step 1:</strong> Create the new table and backfill the data, while keeping the old column intact.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">CreatePhoneNumbers</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">up</span>
    <span class="n">create_table</span> <span class="ss">:phone_numbers</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
      <span class="n">t</span><span class="o">.</span><span class="n">references</span> <span class="ss">:user</span><span class="p">,</span> <span class="ss">null</span><span class="p">:</span> <span class="kp">false</span><span class="p">,</span> <span class="ss">foreign_key</span><span class="p">:</span> <span class="kp">true</span>
      <span class="n">t</span><span class="o">.</span><span class="n">string</span> <span class="ss">:number</span><span class="p">,</span> <span class="ss">null</span><span class="p">:</span> <span class="kp">false</span>
      <span class="n">t</span><span class="o">.</span><span class="n">boolean</span> <span class="ss">:primary</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="kp">true</span>
      <span class="n">t</span><span class="o">.</span><span class="n">timestamps</span>
    <span class="k">end</span>
<span class="err">​</span>
    <span class="n">execute</span> <span class="s">&lt;&lt;-SQL
</span>      <span class="no">INSERT</span> <span class="no">INTO</span> <span class="n">phone_numbers</span> <span class="p">(</span><span class="n">user_id</span><span class="p">,</span> <span class="n">number</span><span class="p">,</span> <span class="n">created_at</span><span class="p">,</span> <span class="n">updated_at</span><span class="p">)</span>
      <span class="no">SELECT</span> <span class="nb">id</span><span class="p">,</span> <span class="n">phone_number</span><span class="p">,</span> <span class="no">NOW</span><span class="p">(),</span> <span class="no">NOW</span><span class="p">()</span>
      <span class="no">FROM</span> <span class="n">users</span>
      <span class="no">WHERE</span> <span class="n">phone_number</span> <span class="no">IS</span> <span class="no">NOT</span> <span class="no">NULL</span>
    <span class="no">SQL</span>
  <span class="k">end</span>
<span class="err">​</span>
  <span class="k">def</span> <span class="nf">down</span>
    <span class="n">drop_table</span> <span class="ss">:phone_numbers</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p><strong>Step 2:</strong> Update the application code to read from and write to the new <code>phone_numbers</code> table. During this transition, you might dual-write to both the old column and the new table to make rollbacks safe.</p>
<p><strong>Step 3:</strong> Once all code uses the new table and the old column is no longer referenced, add it to <code>ignored_columns</code> and deploy.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">ignored_columns</span> <span class="o">+=</span> <span class="o">[</span><span class="s2">&#34;phone_number&#34;</span><span class="o">]</span>
<span class="err">​</span>
  <span class="n">has_many</span> <span class="ss">:phone_numbers</span>
<span class="k">end</span></code></pre>
<p><strong>Step 4:</strong> Drop the column.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">DropPhoneNumberFromUsers</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">remove_column</span> <span class="ss">:users</span><span class="p">,</span> <span class="ss">:phone_number</span><span class="p">,</span> <span class="ss">:string</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Each step is independently deployable and reversible. If something goes wrong at step 2, the old column still has the data. If something breaks at step 3, you remove the <code>ignored_columns</code> entry and the column comes back into view without any data loss.</p>
<p><strong>Note:</strong> It's important to remember that <code>ignored_columns</code> only affects ActiveRecord's view of the schema. Raw SQL queries using <code>execute</code> or <code>find_by_sql</code> that reference the column will still work (or break) based on the actual database state, not the ignored columns list. If you have raw SQL that touches the column, you need to update that code separately.</p>

</div>
]]></content:encoded><pubDate>Thu, 21 May 2026 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/safely-drop-columns-rails-ignored-columns</link><guid isPermaLink="true">https://writesoftwarewell.com/safely-drop-columns-rails-ignored-columns</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Refactoring Databases (in Rails)</title><description>These are my notes from the first few chapters of Refactoring Databases by Scott Ambler and Pramod Sadalage. The book was published in 2006 and its examples are a bit outdated, but the underlying ideas translate well to modern Rails applications where migrations serve as the primary mechanism for schema evolution. A follow-up post will cover additional database refactoring techniques from the later chapters.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>These are my notes from the first few chapters of <a href="https://martinfowler.com/books/refactoringDatabases.html"><em>Refactoring Databases</em></a> by Scott Ambler and Pramod Sadalage. The book was published in 2006 and its examples are a bit outdated, but the underlying ideas translate well to modern Rails applications where migrations serve as the primary mechanism for schema evolution. A follow-up post will cover additional database refactoring techniques from the later chapters.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/tvy2qpz9lajcf0jiijuqky1006kx.jpg" alt="refactoringDatabases.jpg" loading="lazy">
  <figcaption class="attachment__caption">Refactoring Databases</figcaption>
</figure><p>Many of the techniques in this book apply to large production databases with critical or sensitive data, heavy traffic, and zero tolerance for downtime. If you're working on a small app with a handful of users and can afford a maintenance window, a lot of this can be simplified. But the patterns are worth knowing for when you're operating at a scale where you can't just stop the world, run a migration, and hope for the best.</p>
<h2 id="the-case-for-database-refactoring">The case for database refactoring</h2>
<p>Most Rails developers are comfortable refactoring application code. Extract a method, rename a class, move some logic from controller into a model, and so on. The test suite catches regression and you move on. Database schemas deserve the same treatment, but they rarely get it. Renaming a column touches the schema, the models, the queries, the serializers, and possibly an API contract.</p>
<p>Poor design at the data level has a way of rotting everything above it. When the schema doesn't properly represent the domain, you end up writing increasingly contorted application code to paper over structural problems, each workaround making the next feature harder to build. Small, iterative refactorings help you break out of that cycle. They let you evolve the schema alongside the application as your understanding of the domain improves, rather than trying to get the whole thing right up front.</p>
<p>And you will not get it right up front. Requirements shift as projects progress. Any early investment in detailed database architecture gets partially thrown away the moment those requirements change. Rails recognized this years ago, from the beginning. Database migrations treat schema changes as versioned, incremental artifacts applied in sequence, which means the framework already expects your database to evolve over time.</p>
<p>That doesn't mean you should skip modeling entirely. Spending some time early on identifying the main business entities and how they relate to each other is super valuable. The goal is to think through the structural decisions that would be expensive to reverse later, without getting bogged down in column-level details you don't need yet. Work through the specifics on a just-in-time basis as features are built.</p>
<p>The book describes four pillars of evolutionary database development. First, database refactoring itself: evolving the schema a small bit at a time to improve design quality without changing semantics. Second, iterative data modeling: making sure the schema keeps pace with the application code. Third, database regression testing: verifying that the schema actually works. Fourth, developer sandboxes: isolated environments where each developer can experiment before deploying.</p>
<p>In Rails, the first two are handled through migrations and model definitions, the third through your test suite, and the fourth through the convention of each developer running a local database with <code>rails db:create</code> and <code>rails db:migrate</code>.</p>
<h2 id="refactoring-before-adding-features">Refactoring before adding features</h2>
<blockquote>
<p>for each desired change, make the change easy (warning: this may be hard), then make the easy change — Kent Beck</p>
</blockquote>
<p>Here's a discipline worth adopting. When you need to add a new feature, ask yourself whether the current schema is the best possible design for supporting that feature. If it is, go ahead and build. If it isn't, refactor the schema first, then add the feature.</p>
<p>This sounds like it would slow you down, but in practice the opposite happens. If you start with a well-designed schema and refactor continuously to keep it that way, each feature addition becomes straightforward because you're always building on a solid foundation. The alternative, adding features onto a schema that doesn't properly support them, leads to the kind of code where every new query needs three joins and a subselect to work around a table that was never split when it should have been.</p>
<p>Consider a <code>products</code> table with a <code>metadata</code> JSON column that was initially convenient for storing arbitrary attributes. It's okay to begin with, and even works just fine. Then someone needs to build filtering and reporting against specific fields inside that JSON blob. The queries get complicated. Other developers can't figure out what's actually stored in there without reading application code.</p>
<p>Rather than building the filtering feature on top of this and accepting the complexity, the better move is to first extract the relevant fields into proper columns or a related table, migrate the data, update the models, and then build the feature against a schema that properly supports it.</p>
<h2 id="the-process-of-database-refactoring">The process of database refactoring</h2>
<p>Each refactoring should change the schema in one small step. One migration that handles one logical change. If something breaks, you know exactly where it happened.</p>
<p>The process looks like this: verify that the refactoring is actually needed and worth the effort right now, choose the most appropriate refactoring, write the migration, migrate data if the structural change requires it, update the application code (models, queries, tests), and run the test suite. In Rails, the schema change and data migration typically live in the same migration file.</p>
<p>Two principles should govern how you apply refactorings. Smaller changes are safer. The larger a single migration, the more likely you are to introduce a defect and the harder it will be to find. When you need to make a large structural change, decompose it into a sequence of smaller ones. Splitting a table shouldn't be one migration. Create the new table first. Add columns. Migrate data. Update the application code to read from the new table. Remove the old columns in a subsequent migration after verifying everything works. Each step is independently testable and reversible.</p>
<h2 id="structural-refactorings">Structural Refactorings</h2>
<p>These change the shape of tables: dropping, adding, merging, renaming, replacing, or splitting columns and tables. What follows are the techniques from the first few chapters, adapted to how Rails applications actually work.</p>
<h3 id="drop-column">Drop Column</h3>
<p>You drop a column when it's no longer used, or after moving its data somewhere else. The important thing is that by the time the migration runs, nothing should be referencing that column. Search for it in model scopes, raw SQL, serializers, and any gems that might generate queries against it. If you're using <code>select(&quot;*&quot;)</code> anywhere and accessing columns by position rather than name, that code will break when the column count changes.</p>
<p>If the column holds valuable data, move it first. If there's no natural destination, you can preserve it in an archive table keyed by the original table's primary key, though in most Rails apps this situation is uncommon.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Step 1: Stop writing to the column in application code.</span>
<span class="c1"># Tell ActiveRecord to ignore it so cached schema doesn&#39;t break deploys.</span>
<span class="k">class</span> <span class="nc">Contact</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">ignored_columns</span> <span class="o">+=</span> <span class="o">[</span><span class="s2">&#34;fax_number&#34;</span><span class="o">]</span>
<span class="k">end</span>
<span class="err">​</span>
<span class="c1"># Step 2: Deploy the code change above first. Then drop the column.</span>
<span class="k">class</span> <span class="nc">DropFaxNumberFromContacts</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">remove_column</span> <span class="ss">:contacts</span><span class="p">,</span> <span class="ss">:fax_number</span><span class="p">,</span> <span class="ss">:string</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<h3 id="drop-table">Drop Table</h3>
<p>Dropping an entire table requires checking for foreign key constraints, associations in your models, and any raw SQL that references it. If the table holds historically important data and you're not completely certain nothing depends on it, rename it first (something like <code>audit_logs_archived</code>) and let it sit for a transition period. If nothing breaks and nobody comes asking for the data, drop it for real.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">ArchiveAuditLogs</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">up</span>
    <span class="n">rename_table</span> <span class="ss">:audit_logs</span><span class="p">,</span> <span class="ss">:audit_logs_archived</span>
  <span class="k">end</span>
<span class="err">​</span>
  <span class="k">def</span> <span class="nf">down</span>
    <span class="n">rename_table</span> <span class="ss">:audit_logs_archived</span><span class="p">,</span> <span class="ss">:audit_logs</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<h3 id="add-a-calculated-column">Add a Calculated Column</h3>
<p>A calculated column stores a pre-computed value derived from other data: an order total, an average rating, a count of associated records. The point is to avoid recalculating the same thing on every request.</p>
<p>What could go wrong? The calculated value drifts from the source data, and now you have two sources of truth that disagree. Rails gives you a few options for keeping things in sync. ActiveRecord callbacks (or even database triggers) can update the column when the source data changes. For heavier calculations where you can tolerate some lag, a background job that recalculates periodically works well. Which approach you choose depends on how stale you can afford to be.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">AddTotalCentsToOrders</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">add_column</span> <span class="ss">:orders</span><span class="p">,</span> <span class="ss">:total_cents</span><span class="p">,</span> <span class="ss">:integer</span>
<span class="err">​</span>
    <span class="no">Order</span><span class="o">.</span><span class="n">find_each</span> <span class="k">do</span> <span class="o">|</span><span class="n">order</span><span class="o">|</span>
      <span class="n">order</span><span class="o">.</span><span class="n">update_column</span><span class="p">(</span><span class="ss">:total_cents</span><span class="p">,</span> <span class="n">order</span><span class="o">.</span><span class="n">line_items</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="ss">:price_cents</span><span class="p">))</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>After the new calculated column is added, find all the places in the application code where this calculation was being used and update it to use the new column.</p>
<h3 id="move-column">Move Column</h3>
<p>Sometimes a column ends up on the wrong table. Shipping address fields on <code>users</code> need to move to <code>orders</code> or a separate <code>shipping_addresses</code> table once you realize users can have different addresses for different orders. Or you're normalizing to reduce redundancy. Or denormalizing to eliminate a join to improve performance.</p>
<p>The process: add the column on the destination table, backfill the data, update the application to read from and write to the new location, and drop the original column in a later migration. If the data is critical, rename the column and keep it for a while before dropping it.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">ExtractShippingAddressFromUsers</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">up</span>
    <span class="n">create_table</span> <span class="ss">:shipping_addresses</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
      <span class="n">t</span><span class="o">.</span><span class="n">references</span> <span class="ss">:user</span><span class="p">,</span> <span class="ss">null</span><span class="p">:</span> <span class="kp">false</span><span class="p">,</span> <span class="ss">foreign_key</span><span class="p">:</span> <span class="kp">true</span>
      <span class="n">t</span><span class="o">.</span><span class="n">string</span> <span class="ss">:street</span>
      <span class="n">t</span><span class="o">.</span><span class="n">string</span> <span class="ss">:city</span>
      <span class="n">t</span><span class="o">.</span><span class="n">string</span> <span class="ss">:state</span>
      <span class="n">t</span><span class="o">.</span><span class="n">string</span> <span class="ss">:zip</span>
      <span class="n">t</span><span class="o">.</span><span class="n">timestamps</span>
    <span class="k">end</span>
<span class="err">​</span>
    <span class="n">execute</span> <span class="s">&lt;&lt;-SQL
</span>      <span class="no">INSERT</span> <span class="no">INTO</span> <span class="n">shipping_addresses</span> <span class="p">(</span><span class="n">user_id</span><span class="p">,</span> <span class="n">street</span><span class="p">,</span> <span class="n">city</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="n">zip</span><span class="p">,</span> <span class="n">created_at</span><span class="p">,</span> <span class="n">updated_at</span><span class="p">)</span>
      <span class="no">SELECT</span> <span class="nb">id</span><span class="p">,</span> <span class="n">shipping_street</span><span class="p">,</span> <span class="n">shipping_city</span><span class="p">,</span> <span class="n">shipping_state</span><span class="p">,</span> <span class="n">shipping_zip</span><span class="p">,</span> <span class="no">NOW</span><span class="p">(),</span> <span class="no">NOW</span><span class="p">()</span>
      <span class="no">FROM</span> <span class="n">users</span>
      <span class="no">WHERE</span> <span class="n">shipping_street</span> <span class="no">IS</span> <span class="no">NOT</span> <span class="no">NULL</span>
    <span class="no">SQL</span>
  <span class="k">end</span>
<span class="err">​</span>
  <span class="k">def</span> <span class="nf">down</span>
    <span class="n">rename_table</span> <span class="ss">:shipping_addresses</span><span class="p">,</span> <span class="ss">:archived_shipping_addresses</span>
    <span class="c1"># OR</span>
    <span class="n">drop_table</span> <span class="ss">:shipping_addresses</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<h3 id="rename-column">Rename Column</h3>
<p>Renaming a column is often done to improve the readability of your schema. For columns that are part of an API contract or shared across services, or contain huge amounts of critical data, the safer approach is to add a new column with the better name, backfill data, update the application, verify nothing breaks, and then rename and finally drop the old column.</p>
<p>One column name to watch out for: <code>type</code>. Rails reserves it for Single Table Inheritance. A <code>type</code> column that isn't being used for STI will conflict with ActiveRecord's expectations and should be renamed.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Step 1: Add the new column and backfill existing data.</span>
<span class="k">class</span> <span class="nc">AddRoleToUsers</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">add_column</span> <span class="ss">:users</span><span class="p">,</span> <span class="ss">:role</span><span class="p">,</span> <span class="ss">:string</span>
<span class="err">​</span>
    <span class="n">execute</span> <span class="s">&lt;&lt;-SQL
</span>      <span class="no">UPDATE</span> <span class="n">users</span> <span class="no">SET</span> <span class="n">role</span> <span class="o">=</span> <span class="n">type</span>
    <span class="no">SQL</span>
  <span class="k">end</span>
<span class="k">end</span>
<span class="err">​</span>
<span class="c1"># Step 2: Update application code to read from and write to `role`.</span>
<span class="c1"># Dual-write to both columns during the transition so rolling back</span>
<span class="c1"># the deploy doesn&#39;t lose data written after the migration ran.</span>
<span class="err">​</span>
<span class="c1"># Step 3: Once all code reads from `role`, archive the old column.</span>
<span class="k">class</span> <span class="nc">ArchiveTypeOnUsers</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">rename_column</span> <span class="ss">:users</span><span class="p">,</span> <span class="ss">:type</span><span class="p">,</span> <span class="ss">:archived_type</span>
  <span class="k">end</span>
<span class="k">end</span>
<span class="err">​</span>
<span class="c1"># Step 4: After a transition period with no issues, drop it.</span>
<span class="k">class</span> <span class="nc">DropArchivedTypeFromUsers</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">remove_column</span> <span class="ss">:users</span><span class="p">,</span> <span class="ss">:archived_type</span><span class="p">,</span> <span class="ss">:string</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<h3 id="replace-json-column-with-a-table">Replace JSON column with a table</h3>
<p>This is the modern version of what the book calls &quot;Replace Large Object with Table.&quot; A <code>jsonb</code> column that started as a convenient way to store semi-structured data has, over time, developed into a structure you now understand well enough to model properly.</p>
<p>Extracting JSON into a table gives you real indexing, foreign key constraints, database-level validations, and queries that don't require Postgres-specific JSON operators. If the JSON blob duplicates data that exists elsewhere in your database, the extraction also eliminates that redundancy and the integrity problems that come with it.</p>
<p>The process: analyze the JSON structure, design the target table schema, write a migration that creates the table and deserializes each blob into rows, and update the application to use the new association. Rename the old JSON column to verify nothing still depends on it, and eventually drop it.</p>
<p>Say you have a <code>products</code> table with a <code>details</code> jsonb column that stores things like <code>{ &quot;color&quot;: &quot;red&quot;, &quot;weight_grams&quot;: 450, &quot;dimensions&quot;: { &quot;length&quot;: 10, &quot;width&quot;: 5 } }</code>. Over time, you realize these fields are queried frequently and would benefit from proper columns and indexing.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Step 1: Create the new table and backfill from the JSON column.</span>
<span class="k">class</span> <span class="nc">ExtractProductDetails</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">up</span>
    <span class="n">create_table</span> <span class="ss">:product_details</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
      <span class="n">t</span><span class="o">.</span><span class="n">references</span> <span class="ss">:product</span><span class="p">,</span> <span class="ss">null</span><span class="p">:</span> <span class="kp">false</span><span class="p">,</span> <span class="ss">foreign_key</span><span class="p">:</span> <span class="kp">true</span><span class="p">,</span> <span class="ss">index</span><span class="p">:</span> <span class="p">{</span> <span class="ss">unique</span><span class="p">:</span> <span class="kp">true</span> <span class="p">}</span>
      <span class="n">t</span><span class="o">.</span><span class="n">string</span> <span class="ss">:color</span>
      <span class="n">t</span><span class="o">.</span><span class="n">integer</span> <span class="ss">:weight_grams</span>
      <span class="n">t</span><span class="o">.</span><span class="n">integer</span> <span class="ss">:length</span>
      <span class="n">t</span><span class="o">.</span><span class="n">integer</span> <span class="ss">:width</span>
      <span class="n">t</span><span class="o">.</span><span class="n">timestamps</span>
    <span class="k">end</span>
<span class="err">​</span>
    <span class="n">execute</span> <span class="s">&lt;&lt;-SQL
</span>      <span class="no">INSERT</span> <span class="no">INTO</span> <span class="n">product_details</span>
        <span class="p">(</span><span class="n">product_id</span><span class="p">,</span> <span class="n">color</span><span class="p">,</span> <span class="n">weight_grams</span><span class="p">,</span> <span class="n">length</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">created_at</span><span class="p">,</span> <span class="n">updated_at</span><span class="p">)</span>
      <span class="no">SELECT</span>
        <span class="nb">id</span><span class="p">,</span>
        <span class="n">details</span><span class="o">-&gt;&gt;</span><span class="s1">&#39;color&#39;</span><span class="p">,</span>
        <span class="p">(</span><span class="n">details</span><span class="o">-&gt;&gt;</span><span class="s1">&#39;weight_grams&#39;</span><span class="p">)</span><span class="o">::</span><span class="n">integer</span><span class="p">,</span>
        <span class="p">(</span><span class="n">details</span><span class="o">-&gt;</span><span class="s1">&#39;dimensions&#39;</span><span class="o">-&gt;&gt;</span><span class="s1">&#39;length&#39;</span><span class="p">)</span><span class="o">::</span><span class="n">integer</span><span class="p">,</span>
        <span class="p">(</span><span class="n">details</span><span class="o">-&gt;</span><span class="s1">&#39;dimensions&#39;</span><span class="o">-&gt;&gt;</span><span class="s1">&#39;width&#39;</span><span class="p">)</span><span class="o">::</span><span class="n">integer</span><span class="p">,</span>
        <span class="no">NOW</span><span class="p">(),</span> <span class="no">NOW</span><span class="p">()</span>
      <span class="no">FROM</span> <span class="n">products</span>
      <span class="no">WHERE</span> <span class="n">details</span> <span class="no">IS</span> <span class="no">NOT</span> <span class="no">NULL</span>
    <span class="no">SQL</span>
  <span class="k">end</span>
<span class="err">​</span>
  <span class="k">def</span> <span class="nf">down</span>
    <span class="n">drop_table</span> <span class="ss">:product_details</span>
  <span class="k">end</span>
<span class="k">end</span>
<span class="err">​</span>
<span class="c1"># Step 2: Update models and application code to use the new association.</span>
<span class="c1"># Dual-write to both the JSON column and the new table during transition.</span>
<span class="err">​</span>
<span class="c1"># Step 3: Rename the JSON column to confirm nothing depends on it.</span>
<span class="k">class</span> <span class="nc">ArchiveProductDetailsJson</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">rename_column</span> <span class="ss">:products</span><span class="p">,</span> <span class="ss">:details</span><span class="p">,</span> <span class="ss">:archived_details</span>
  <span class="k">end</span>
<span class="k">end</span>
<span class="err">​</span>
<span class="c1"># Step 4: Drop it after the transition period.</span>
<span class="k">class</span> <span class="nc">DropArchivedDetailsFromProducts</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">change</span>
    <span class="n">remove_column</span> <span class="ss">:products</span><span class="p">,</span> <span class="ss">:archived_details</span><span class="p">,</span> <span class="ss">:jsonb</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<h3 id="replace-one-to-many-with-a-join-table">Replace one-to-many with a join table</h3>
<p>This refactoring prepares a one-to-many relationship to become many-to-many. Say employees currently belong to one manager via a <code>manager_id</code> foreign key. A new business requirement might be: employees need to report to multiple managers. The foreign key on <code>employees</code> can't represent that, so you introduce a join table.</p>
<p>Since one-to-many is a subset of many-to-many, the join table handles both the existing data and the new requirement. It also gives you a place to store metadata about the relationship (when the assignment started, the type of reporting relationship) that doesn't belong on either the <code>employees</code> or <code>managers</code> table.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">CreateManagerAssignments</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="o">[</span><span class="mi">8</span><span class="o">.</span><span class="mi">0</span><span class="o">]</span>
  <span class="k">def</span> <span class="nf">up</span>
    <span class="n">create_table</span> <span class="ss">:manager_assignments</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
      <span class="n">t</span><span class="o">.</span><span class="n">references</span> <span class="ss">:employee</span><span class="p">,</span> <span class="ss">null</span><span class="p">:</span> <span class="kp">false</span><span class="p">,</span> <span class="ss">foreign_key</span><span class="p">:</span> <span class="kp">true</span>
      <span class="n">t</span><span class="o">.</span><span class="n">references</span> <span class="ss">:manager</span><span class="p">,</span> <span class="ss">null</span><span class="p">:</span> <span class="kp">false</span><span class="p">,</span> <span class="ss">foreign_key</span><span class="p">:</span> <span class="p">{</span> <span class="ss">to_table</span><span class="p">:</span> <span class="ss">:employees</span> <span class="p">}</span>
      <span class="n">t</span><span class="o">.</span><span class="n">timestamps</span>
    <span class="k">end</span>
<span class="err">​</span>
    <span class="n">execute</span> <span class="s">&lt;&lt;-SQL
</span>      <span class="no">INSERT</span> <span class="no">INTO</span> <span class="n">manager_assignments</span> <span class="p">(</span><span class="n">employee_id</span><span class="p">,</span> <span class="n">manager_id</span><span class="p">,</span> <span class="n">created_at</span><span class="p">,</span> <span class="n">updated_at</span><span class="p">)</span>
      <span class="no">SELECT</span> <span class="nb">id</span><span class="p">,</span> <span class="n">manager_id</span><span class="p">,</span> <span class="no">NOW</span><span class="p">(),</span> <span class="no">NOW</span><span class="p">()</span>
      <span class="no">FROM</span> <span class="n">employees</span>
      <span class="no">WHERE</span> <span class="n">manager_id</span> <span class="no">IS</span> <span class="no">NOT</span> <span class="no">NULL</span>
    <span class="no">SQL</span>
  <span class="k">end</span>
<span class="err">​</span>
  <span class="k">def</span> <span class="nf">down</span>
    <span class="n">drop_table</span> <span class="ss">:manager_assignments</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Be careful with this one, though. If the relationship genuinely isn't going to become many-to-many, you've added an extra join to every query for no reason and made the schema harder to understand. Build for actual requirements, not speculative ones.</p>
<h3 id="use-surrogate-key">Use Surrogate Key</h3>
<p>A surrogate key is an artificial identifier, typically generated by the system, such as an auto-incrementing ID, UUID, etc. A natural key is derived from real-world data that already exists in the domain, one that has business meaning, e.g. SSN, email, etc.</p>
<p>Rails defaults to surrogate keys through the auto-incrementing <code>id</code> column, so this refactoring mostly comes up when you're inheriting a database from a non-Rails application or when someone previously used a natural key (email, ISBN, SSN) as the primary key.</p>
<p>The problem with natural keys is that they change. A user updates their email address, and suddenly you're cascading foreign key updates across a dozen tables. Natural keys also couple the schema tightly to the business domain in ways that get inconvenient as the domain evolves.</p>
<p>The fix is to add a surrogate key column, populate it with unique values, add a unique index, and update all foreign key references. The original natural key column stays in the table with its unique constraint; it just stops being the primary key. This touches a lot of tables if the natural key was widely referenced, so plan to split it across multiple deployments.</p>
<hr>
<p>The main idea from these chapters is that the database schema should be treated as a living artifact that evolves alongside the application through small, deliberate refactorings.</p>
<p>Rails already gives you the migration infrastructure. The important thing is to think about the schema changes and how they'll affect the data and the application, and then apply refactorings proactively (improving the schema before adding features), decomposing large changes into sequences of small ones, and resisting the temptation to work around structural deficiencies with increasingly complex application code.</p>
<p>The next post will cover data quality refactorings, referential integrity techniques, architectural refactorings, and much more.</p>

</div>
]]></content:encoded><pubDate>Sat, 18 Apr 2026 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/refactoring-databases-in-rails</link><guid isPermaLink="true">https://writesoftwarewell.com/refactoring-databases-in-rails</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Finally, the Rails Blog Runs on Rails</title><description>Last year, I announced plans to rewrite this blog in Ruby on Rails. It was hosted on Ghost for all these years (which is built with Node.js), and the idea was to rebuild it from scratch in Rails and write about the process as I went along. I even published a few posts as I started development.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>Last year, I announced plans to rewrite this blog in Ruby on Rails. It was hosted on Ghost for all these years (which is built with Node.js), and the idea was to rebuild it from scratch in Rails and write about the process as I went along. I even published a few posts as I started development.</p>
<p>However, as you may have noticed, I haven't published consistently for the past six to eight months. What's more, for the last two months, I haven't even written a single post.</p>
<p>Part of the reason is AI, and the proliferation of AI-generated writing everywhere which completely killed my motivation to write. Why spend hours and even days writing a detailed technical blog post when Claude or ChatGPT can explain the same topic in more depth, with analogies and examples, and you can keep asking it to explain the parts you didn't understand? A static blog post can't do that.</p>
<p>I really think the era of generic technical how-to blog posts is over, and I didn't want to contribute to the ongoing slop on the web with AI generated blog posts with zero efforts. So I stopped writing the kind of explanatory technical posts I used to write after learning something new.</p>
<p>On the flip side, while AI-assisted writing killed my motivation to write, AI-assisted agentic coding did the exact opposite. It made me fall in love with programming and building again.</p>
<p>As I started rebuilding the blog, the pace of building quickly outpaced the pace of writing. Every time I sat down to write one over the past two months, it felt like I could use that time to learn something new or build something with agents. The pace of AI-enabled learning and agentic coding is so much faster now that writing about it can't keep up. I'd rather spend that hour making progress than documenting progress I already made.</p>
<p>My AI-journey started with Copilot, but I quickly switched to Cursor and used that for a few months, before trying Claude Code last year. After paying for Claude PRO for the past six months, I finally upgraded to Claude Max last week. Easiest $140 subscription purchase I've ever made.</p>
<p>At this time, I can't even imagine going back to working without Claude Code. Even $140 a month feels like a steal to have an excellent and patient senior programmer working along with me, answering all my questions, patiently explaining codebases and obscure APIs, and doing much, much more without ever getting tired. Agentic coding with a token efficient language and framework like Ruby on Rails is pure joy!</p>
<p>Anyways, back to the blog. Since I won't be publishing much going forward, it only made sense to self-host everything to avoid the recurring costs. After working on the blog in short bits and pieces in my free time, finally it's at the stage where I felt confident enough to switch the domain over.</p>
<p>As of yesterday, the blog is running as a full-stack Rails + Hotwire application, backed by PostgreSQL, self-hosted on a Hetzner server, deployed with Kamal, with Postgres running as a Kamal accessory.</p>
<p>Email delivery is handled by <a href="https://www.smtp2go.com/">SMTP2GO</a>, which I've become a huge fan of. It lets you send both transactional and marketing emails via SMTP. I initially went with Kit (previously ConvertKit) and even implemented the complete API integration, but then decided it was worth handling all the email marketing myself and learn about email delivery in the process.</p>
<p>As I learned while building, even a simple blogging CMS has a lot of interesting stuff going on beneath the surface. I built the initial CRUD part, where I could write and publish posts, in a few hours with Claude. But building the admin dashboard, subscriber management, email delivery, the subscribe/unsubscribe flow, and newsletter publishing took a while to implement, even with Claude.</p>
<p>Most time-consuming of all was importing the 225 posts from the old blog. Ghost's export doesn't make this easy, so I had to copy and paste each post along with its images manually. The old blog also had a ton of interesting comments and I didn't want to lose all that history, so I built a subscriber impersonation feature and manually added all of them. It's been a fun trip building the whole thing from scratch and reducing my costs by 10x along the way.</p>
<p>Anyways, so that's what I've been up to for the past few months. As software developers, we're truly living in wonderful times. Never been a better time to be a developer.</p>
<p>As for the blog, I'm still not sure what I'll write about going forward. The generic technical how-to posts feel pointless now, as I mentioned earlier. But I do want to start writing again. Maybe less about how to use the Rails Router and more about the personal side of software development, like running a consultancy, working with agents all day, and deal with all the non-code software stuff that nobody teaches you.</p>
<p>So we'll see :)</p>

</div>
]]></content:encoded><pubDate>Tue, 31 Mar 2026 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/finally-the-rails-blog-runs-on-rails</link><guid isPermaLink="true">https://writesoftwarewell.com/finally-the-rails-blog-runs-on-rails</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Understanding ActiveStorage Variants for Image Transformations in Rails</title><description>Image transformations let you show images in the size or format you need. You can create a new version by calling variant on an attachment and passing the desired transformations. When a browser requests that URL, Rails will process the original image on demand and redirect to the generated file.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <blockquote>
<p><em>This post is part of a series on Active Storage internals. See also:</em> <a href="https://writesoftwarewell.com/active-storage-domain-model-blobs-attachments"><em>Understanding the Active Storage Domain Model</em></a> <em>and</em> <a href="https://writesoftwarewell.com/active-storage-has-one-attached-internals-dsl"><em>Understanding has_one_attached</em></a><em>.</em></p>
</blockquote>
<p><strong>Disclaimer:</strong> I used Claude Code to trace through the Rails codebase and explain how various parts of it are related to each other. Lately, I've found it an excellent tool to navigate the parts of the codebase that I don't understand and to get a deeper understanding of how things work. It's such a fun process to come across some obscure Rails method, ask Claude (or Cursor) to explain exactly how it works, and learn a few new things in the way. In the past, I would have likely skimmed past it or ignored it altogether.</p>
<p>It's so easy to confuse access to knowledge with having understanding. <a href="https://writesoftwarewell.com/vibe-learning-is-underrated">Vibe learning</a> is even better than vibe coding.</p>
<hr>
<p>If you've worked on an application that had file uploads, you've likely needed to display images at different sizes. A full-resolution avatar doesn't make sense when you want to show dozens of users' thumbnails on a single page. That's where you need to transform the original image to different variants.</p>
<p>But what actually happens when you call <code>user.avatar.variant(:thumb)</code>? Where does the transformed image get stored? How does Rails know not to regenerate it on every request?</p>
<p>I had these questions ever since I worked with ActiveStorage, so I decided to trace through the source code to learn how variants work. This post documents the end-to-end workflow. As always, I recommend having the <a href="https://github.com/rails/rails/tree/main/activestorage">Rails source code</a> open on the side while reading.</p>
<h2 id="overview">Overview</h2>
<p>Before we dive into the source, here's a high-level overview of the important objects involved:</p>
<ol>
<li><strong>Variant</strong> - A transformed version of an image blob (resized, cropped, converted, etc.)</li>
<li><strong>Variation</strong> - The transformation instructions (a set of operations like <code>resize_to_limit: [100, 100]</code>)</li>
<li><strong>VariantRecord</strong> - Optional database tracking of generated variants</li>
<li><strong>Transformer</strong> - The actual image processing engine (Vips or ImageMagick)</li>
</ol>
<p>When you call <code>variant(:thumb)</code>, Rails doesn't immediately process the image. It returns a <code>Variant</code> object that represents the <em>intention</em> to transform. The actual processing happens lazily when the variant URL is first requested.</p>
<pre data-language="text"><code class="code-inline language-text">attachment.variant(:thumb)
    ↓
Returns Variant object (no processing yet)
    ↓
URL requested by browser
    ↓
Controller calls variant.processed
    ↓
Image downloaded, transformed, re-uploaded
    ↓
Subsequent requests served from storage</code></pre>
<p>Let's walk through each piece.</p>
<h2 id="dsl-to-define-variants">DSL to Define Variants</h2>
<p>You define named variants in your model as follows:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">has_one_attached</span> <span class="ss">:avatar</span> <span class="k">do</span> <span class="o">|</span><span class="n">attachable</span><span class="o">|</span>
    <span class="n">attachable</span><span class="o">.</span><span class="n">variant</span> <span class="ss">:thumb</span><span class="p">,</span> <span class="ss">resize_to_limit</span><span class="p">:</span> <span class="o">[</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="o">]</span>
    <span class="n">attachable</span><span class="o">.</span><span class="n">variant</span> <span class="ss">:medium</span><span class="p">,</span> <span class="ss">resize_to_limit</span><span class="p">:</span> <span class="o">[</span><span class="mi">500</span><span class="p">,</span> <span class="mi">500</span><span class="o">]</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This registers named variants through the attachment reflection. The block yields an <code>Attachable</code> object that collects variant definitions.</p>
<p>When you call <code>user.avatar.variant(:thumb)</code>, the <code>Attachment#variant</code> method looks up the named variant and extracts its transformations:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/models/active_storage/attachment.rb</span>
<span class="k">def</span> <span class="nf">variant</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span>
  <span class="n">transformations</span> <span class="o">=</span> <span class="n">transformations_by_name</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span>
  <span class="n">blob</span><span class="o">.</span><span class="n">variant</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span>
<span class="k">end</span>

<span class="kp">private</span>
  <span class="k">def</span> <span class="nf">transformations_by_name</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span>
    <span class="k">case</span> <span class="n">transformations</span>
    <span class="k">when</span> <span class="no">Symbol</span>
      <span class="n">named_variants</span><span class="o">.</span><span class="n">fetch</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span> <span class="k">do</span>
        <span class="k">raise</span> <span class="no">ArgumentError</span><span class="p">,</span> <span class="s2">&#34;Cannot find variant :</span><span class="si">#{</span><span class="n">transformations</span><span class="si">}</span><span class="s2">...&#34;</span>
      <span class="k">end</span><span class="o">.</span><span class="n">transformations</span>
    <span class="k">else</span>
      <span class="n">transformations</span>
    <span class="k">end</span>
  <span class="k">end</span></code></pre>
<p>So <code>variant(:thumb)</code> becomes <code>variant(resize_to_limit: [100, 100])</code>, which is then delegated to the blob.</p>
<h2 id="the-blob-creates-variant-objects">The Blob Creates Variant Objects</h2>
<p>The blob receives the transformation hash and creates a Variant object. This happens in the <code>Representable</code> concern:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/models/active_storage/blob/representable.rb</span>
<span class="k">def</span> <span class="nf">variant</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span>
  <span class="k">if</span> <span class="n">variable?</span>
    <span class="n">variant_class</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="nb">self</span><span class="p">,</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Variation</span><span class="o">.</span><span class="n">wrap</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span><span class="o">.</span><span class="n">default_to</span><span class="p">(</span><span class="n">default_variant_transformations</span><span class="p">))</span>
  <span class="k">else</span>
    <span class="k">raise</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">InvariableError</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>A few things happen here:</p>
<ol>
<li><strong><code>variable?</code></strong> checks if the blob's content type supports transformations. Only image types in <code>ActiveStorage.variable_content_types</code> qualify. Try to call <code>variant</code> on a PDF and you'll get an <code>InvariableError</code>.</li>
<li><strong><code>Variation.wrap</code></strong> converts the hash into a <code>Variation</code> object (more on this shortly).</li>
<li><strong><code>default_to</code></strong> applies default transformations. Notably, non-web-safe images default to PNG format.</li>
<li><strong><code>variant_class</code></strong> returns either <code>Variant</code> or <code>VariantWithRecord</code> depending on configuration:</li>
</ol>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">variant_class</span>
  <span class="no">ActiveStorage</span><span class="o">.</span><span class="n">track_variants</span> <span class="p">?</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">VariantWithRecord</span> <span class="p">:</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Variant</span>
<span class="k">end</span></code></pre>
<p>The <code>track_variants</code> setting determines whether Rails stores variant metadata in the database. We'll explore both classes.</p>
<h2 id="variation-class-encodes-transformations">Variation Class Encodes Transformations</h2>
<p><code>Variation</code> encapsulates the transformation instructions and handles their serialization. This is important because variant URLs need to include the transformation parameters in a tamper-proof way.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/models/active_storage/variation.rb</span>
<span class="k">class</span> <span class="nc">Variation</span>
  <span class="kp">attr_reader</span> <span class="ss">:transformations</span>

  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">wrap</span><span class="p">(</span><span class="n">variator</span><span class="p">)</span>
    <span class="k">case</span> <span class="n">variator</span>
    <span class="k">when</span> <span class="nb">self</span> <span class="k">then</span> <span class="n">variator</span>
    <span class="k">when</span> <span class="no">Hash</span> <span class="k">then</span> <span class="kp">new</span><span class="p">(</span><span class="n">variator</span><span class="p">)</span>
    <span class="k">when</span> <span class="nb">String</span> <span class="k">then</span> <span class="n">decode</span><span class="p">(</span><span class="n">variator</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">key</span>
    <span class="nb">self</span><span class="o">.</span><span class="n">class</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">encode</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span>
    <span class="no">ActiveStorage</span><span class="o">.</span><span class="n">verifier</span><span class="o">.</span><span class="n">generate</span><span class="p">(</span><span class="n">transformations</span><span class="p">,</span> <span class="ss">purpose</span><span class="p">:</span> <span class="ss">:variation</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">decode</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
    <span class="kp">new</span><span class="p">(</span><span class="no">ActiveStorage</span><span class="o">.</span><span class="n">verifier</span><span class="o">.</span><span class="n">verify</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="ss">purpose</span><span class="p">:</span> <span class="ss">:variation</span><span class="p">))</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p><strong>The</strong> <strong><code>key</code></strong> <strong>method generates a signed, URL-safe representation of the transformations. This is what appears in variant URLs.</strong> When a request comes in, Rails decodes the key using <code>MessageVerifier</code> and reconstructs the <code>Variation</code> object.</p>
<p>This signing prevents tampering. Without it, an attacker could modify transformation parameters in the URL to trigger arbitrary image operations.</p>
<p>The <code>Variation</code> also handles the actual transformation:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">transform</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">block</span><span class="p">)</span>
  <span class="n">transformer</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="nb">format</span><span class="p">:</span> <span class="nb">format</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">block</span><span class="p">)</span>
<span class="k">end</span>

<span class="kp">private</span>
  <span class="k">def</span> <span class="nf">transformer</span>
    <span class="no">ActiveStorage</span><span class="o">.</span><span class="n">variant_transformer</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">transformations</span><span class="o">.</span><span class="n">except</span><span class="p">(</span><span class="ss">:format</span><span class="p">))</span>
  <span class="k">end</span></code></pre>
<p>Note: The format option is intentionally excluded from the transformations passed to the transformer constructor because it's handled separately. This separation exists because format serves a different purpose than transformations:</p>
<ol>
<li>Transformations (like resize_to_limit, colourspace, rotate) are image processing operations that modify the image content</li>
<li>Format specifies the output file format (png, jpg, webp, etc.) - it's not an image manipulation but rather an output specification</li>
</ol>
<p>In ImageProcessing (which Active Storage uses under the hood), the format is typically specified when saving/outputting the final result, not as part of the transformation pipeline. By excluding it from the transformations hash and passing it separately, the code keeps these concerns cleanly separated.</p>
<h2 id="the-variant-class-lazy-processing">The Variant Class: Lazy Processing</h2>
<p>The <code>Variant</code> class represents a specific blob with specific transformations. It's intentionally lazy.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/models/active_storage/variant.rb</span>
<span class="k">class</span> <span class="nc">Variant</span>
  <span class="kp">attr_reader</span> <span class="ss">:blob</span><span class="p">,</span> <span class="ss">:variation</span>

  <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">blob</span><span class="p">,</span> <span class="n">variation</span><span class="p">)</span>
    <span class="vi">@blob</span><span class="p">,</span> <span class="vi">@variation</span> <span class="o">=</span> <span class="n">blob</span><span class="p">,</span> <span class="n">variation</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">processed</span>
    <span class="n">process</span> <span class="k">unless</span> <span class="n">processed?</span>
    <span class="nb">self</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">processed?</span>
    <span class="n">service</span><span class="o">.</span><span class="n">exist?</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Notice that <code>processed?</code> checks if a file exists at the variant's key in the storage service. There's no database query, just a service existence check.</p>
<p>The <code>key</code> method generates a unique identifier for this variant:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">key</span>
  <span class="s2">&#34;variants/</span><span class="si">#{</span><span class="n">blob</span><span class="o">.</span><span class="n">key</span><span class="si">}</span><span class="s2">/</span><span class="si">#{</span><span class="no">OpenSSL</span><span class="o">::</span><span class="no">Digest</span><span class="o">::</span><span class="no">SHA256</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">(</span><span class="n">variation</span><span class="o">.</span><span class="n">key</span><span class="p">)</span><span class="si">}</span><span class="s2">&#34;</span>
<span class="k">end</span></code></pre>
<p>The key combines:</p>
<ul>
<li>The original blob's key</li>
<li>A SHA256 hash of the signed variation key</li>
</ul>
<p>This is to ensure that each unique transformation of each blob has its own storage location.</p>
<h3 id="the-processing-flow">The Processing Flow</h3>
<p>When <code>processed</code> is called and the variant doesn't exist:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">process</span>
  <span class="n">blob</span><span class="o">.</span><span class="n">open</span> <span class="k">do</span> <span class="o">|</span><span class="n">input</span><span class="o">|</span>
    <span class="n">variation</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">input</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">output</span><span class="o">|</span>
      <span class="n">service</span><span class="o">.</span><span class="n">upload</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="ss">content_type</span><span class="p">:</span> <span class="n">content_type</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<ol>
<li>Download the original blob from storage</li>
<li>Pass it to <code>Variation#transform</code></li>
<li>Upload the result to storage under the variant key</li>
</ol>
<p>Once uploaded, subsequent calls to <code>processed?</code> return true, and the variant is served directly from storage.</p>
<h2 id="variantwithrecord-database-backed-tracking">VariantWithRecord: Database-Backed Tracking</h2>
<p>The basic <code>Variant</code> class works, but it has a limitation: the only way to know if a variant exists is to ask the storage service. This can be slow for certain services and makes it hard to query which variants exist.</p>
<p><code>VariantWithRecord</code> adds database tracking:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/models/active_storage/variant_with_record.rb</span>
<span class="k">class</span> <span class="nc">VariantWithRecord</span>
  <span class="k">def</span> <span class="nf">processed?</span>
    <span class="n">record</span><span class="o">.</span><span class="n">present?</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">process</span>
    <span class="n">transform_blob</span> <span class="p">{</span> <span class="o">|</span><span class="n">image</span><span class="o">|</span> <span class="n">create_or_find_record</span><span class="p">(</span><span class="ss">image</span><span class="p">:</span> <span class="n">image</span><span class="p">)</span> <span class="p">}</span>
  <span class="k">end</span>

  <span class="kp">private</span>
    <span class="k">def</span> <span class="nf">create_or_find_record</span><span class="p">(</span><span class="ss">image</span><span class="p">:)</span>
      <span class="vi">@record</span> <span class="o">=</span> <span class="n">blob</span><span class="o">.</span><span class="n">variant_records</span><span class="o">.</span><span class="n">create_or_find_by!</span><span class="p">(</span><span class="ss">variation_digest</span><span class="p">:</span> <span class="n">variation</span><span class="o">.</span><span class="n">digest</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">record</span><span class="o">|</span>
        <span class="n">record</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">image</span><span class="p">)</span>
      <span class="k">end</span>
    <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Instead of checking service existence, it checks for a <code>VariantRecord</code> in the database. The <code>variation_digest</code> (a SHA1 hash of the transformations) ensures idempotency.</p>
<p>The <code>VariantRecord</code> model is simple:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/models/active_storage/variant_record.rb</span>
<span class="k">class</span> <span class="nc">VariantRecord</span> <span class="o">&lt;</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Record</span>
  <span class="n">belongs_to</span> <span class="ss">:blob</span>
  <span class="n">has_one_attached</span> <span class="ss">:image</span>
<span class="k">end</span></code></pre>
<p>Each <code>VariantRecord</code> has its own attached image—the processed variant. This is an interesting design: variants are stored as attachments themselves, using the same Active Storage machinery.</p>
<p>Enable this with:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># config/application.rb</span>
<span class="n">config</span><span class="o">.</span><span class="n">active_storage</span><span class="o">.</span><span class="n">track_variants</span> <span class="o">=</span> <span class="kp">true</span></code></pre>
<h2 id="transformers-process-the-image">Transformers Process the Image</h2>
<p>The actual image processing is delegated to transformer classes. Rails ships with two options.</p>
<h4 id="vips-transformer-default-in-rails-7">Vips Transformer (Default in Rails 7+)</h4>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># lib/active_storage/transformers/vips.rb</span>
<span class="k">class</span> <span class="nc">Vips</span> <span class="o">&lt;</span> <span class="no">ImageProcessingTransformer</span>
  <span class="kp">private</span>
    <span class="k">def</span> <span class="nf">processor</span>
      <span class="no">ImageProcessing</span><span class="o">::</span><span class="no">Vips</span>
    <span class="k">end</span>
<span class="k">end</span></code></pre>
<h4 id="imagemagick-transformer">ImageMagick Transformer</h4>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># lib/active_storage/transformers/image_magick.rb</span>
<span class="k">class</span> <span class="nc">ImageMagick</span> <span class="o">&lt;</span> <span class="no">ImageProcessingTransformer</span>
  <span class="kp">private</span>
    <span class="k">def</span> <span class="nf">processor</span>
      <span class="no">ImageProcessing</span><span class="o">::</span><span class="no">MiniMagick</span>
    <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Both inherit from <code>ImageProcessingTransformer</code>, which uses the <a href="https://github.com/janko/image_processing">image_processing</a> gem:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># lib/active_storage/transformers/image_processing_transformer.rb</span>
<span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="nb">format</span><span class="p">:)</span>
  <span class="n">processor</span><span class="o">.</span>
    <span class="n">source</span><span class="p">(</span><span class="n">file</span><span class="p">)</span><span class="o">.</span>
    <span class="n">loader</span><span class="p">(</span><span class="ss">page</span><span class="p">:</span> <span class="mi">0</span><span class="p">)</span><span class="o">.</span>
    <span class="n">convert</span><span class="p">(</span><span class="nb">format</span><span class="p">)</span><span class="o">.</span>
    <span class="n">apply</span><span class="p">(</span><span class="n">operations</span><span class="p">)</span><span class="o">.</span>
    <span class="n">call</span>
<span class="k">end</span></code></pre>
<p>The <code>loader(page: 0)</code> loads only the first page, which matters for animated GIFs and multi-page documents.</p>
<h3 id="security-validations">Security Validations</h3>
<p>The transformer validates operations to prevent command injection:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">validate_transformation</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">argument</span><span class="p">)</span>
  <span class="k">unless</span> <span class="no">ActiveStorage</span><span class="o">.</span><span class="n">supported_image_processing_methods</span><span class="o">.</span><span class="n">include?</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
    <span class="k">raise</span> <span class="no">ArgumentError</span><span class="p">,</span> <span class="s2">&#34;Unsupported transformation: </span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span>
  <span class="k">end</span>

  <span class="n">validate_transformation_argument</span><span class="p">(</span><span class="n">argument</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<p>This is why the docs warn that &quot;It should be considered unsafe to provide arbitrary user-supplied transformations.&quot;</p>
<p>Configure the processor in your application:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">config</span><span class="o">.</span><span class="n">active_storage</span><span class="o">.</span><span class="n">variant_processor</span> <span class="o">=</span> <span class="ss">:vips</span>  <span class="c1"># or :mini_magick</span></code></pre>
<h2 id="controllers-serve-the-variants">Controllers Serve the Variants</h2>
<p>When you render a variant in a view:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="o">&lt;%=</span> <span class="n">image_tag</span> <span class="n">user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">variant</span><span class="p">(</span><span class="ss">:thumb</span><span class="p">)</span> <span class="o">%&gt;</span></code></pre>
<p>Rails generates a URL pointing to one of two controllers.</p>
<h4 id="redirectcontroller-default">RedirectController (Default)</h4>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/controllers/active_storage/representations/redirect_controller.rb</span>
<span class="k">def</span> <span class="nf">show</span>
  <span class="n">expires_in</span> <span class="no">ActiveStorage</span><span class="o">.</span><span class="n">service_urls_expire_in</span>
  <span class="n">redirect_to</span> <span class="vi">@representation</span><span class="o">.</span><span class="n">url</span><span class="p">(</span><span class="ss">disposition</span><span class="p">:</span> <span class="n">params</span><span class="o">[</span><span class="ss">:disposition</span><span class="o">]</span><span class="p">),</span> <span class="ss">allow_other_host</span><span class="p">:</span> <span class="kp">true</span>
<span class="k">end</span></code></pre>
<p>This generates a temporary URL (default: 5 minutes) and redirects to the storage service. The actual file is served by S3, GCS, etc.</p>
<h4 id="proxycontroller">ProxyController</h4>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/controllers/active_storage/representations/proxy_controller.rb</span>
<span class="k">def</span> <span class="nf">show</span>
  <span class="n">http_cache_forever</span> <span class="kp">public</span><span class="p">:</span> <span class="kp">true</span> <span class="k">do</span>
    <span class="n">send_blob_stream</span> <span class="vi">@representation</span><span class="p">,</span> <span class="ss">disposition</span><span class="p">:</span> <span class="n">params</span><span class="o">[</span><span class="ss">:disposition</span><span class="o">]</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This streams the file through your Rails server. It sets <code>Cache-Control: public, max-age=31536000</code> because the URL contains the variation hash. If transformations change, the URL changes.</p>
<p>Both controllers inherit from <code>BaseController</code>, which handles the processing:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/controllers/active_storage/representations/base_controller.rb</span>
<span class="kp">private</span>
  <span class="k">def</span> <span class="nf">set_representation</span>
    <span class="vi">@representation</span> <span class="o">=</span> <span class="vi">@blob</span><span class="o">.</span><span class="n">representation</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:variation_key</span><span class="o">]</span><span class="p">)</span><span class="o">.</span><span class="n">processed</span>
  <span class="k">end</span></code></pre>
<p>The <code>.processed</code> call triggers lazy processing on first request. Subsequent requests skip processing since the variant already exists.</p>
<h2 id="preprocessed-variants-avoiding-lazy-loading">Preprocessed Variants: Avoiding Lazy Loading</h2>
<p>Lazy processing works well, but the first user to request a variant pays the processing cost. For high-traffic images, you can pre-process variants:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">has_one_attached</span> <span class="ss">:avatar</span> <span class="k">do</span> <span class="o">|</span><span class="n">attachable</span><span class="o">|</span>
    <span class="n">attachable</span><span class="o">.</span><span class="n">variant</span> <span class="ss">:thumb</span><span class="p">,</span> <span class="ss">resize_to_limit</span><span class="p">:</span> <span class="o">[</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="o">]</span><span class="p">,</span> <span class="ss">preprocessed</span><span class="p">:</span> <span class="kp">true</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>When <code>preprocessed: true</code>, Rails enqueues a job immediately after upload:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/jobs/active_storage/transform_job.rb</span>
<span class="k">class</span> <span class="nc">TransformJob</span> <span class="o">&lt;</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">BaseJob</span>
  <span class="k">def</span> <span class="nf">perform</span><span class="p">(</span><span class="n">blob</span><span class="p">,</span> <span class="n">transformations</span><span class="p">)</span>
    <span class="n">blob</span><span class="o">.</span><span class="n">variant</span><span class="p">(</span><span class="n">transformations</span><span class="p">)</span><span class="o">.</span><span class="n">processed</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p><strong>Important: The</strong> <strong><code>:preprocessed</code></strong> <strong>option is deprecated and will be removed in Rails 9.0.</strong> Use the <code>:process</code> option which provides more control.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">attachable</span><span class="o">.</span><span class="n">variant</span> <span class="ss">:thumb</span><span class="p">,</span> <span class="ss">resize_to_limit</span><span class="p">:</span> <span class="o">[</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="o">]</span><span class="p">,</span> <span class="ss">process</span><span class="p">:</span> <span class="ss">:immediately</span></code></pre>
<ul>
<li><code>:lazily</code> (default) - Process on first request</li>
<li><code>:later</code> - Process via background job after upload</li>
<li><code>:immediately</code> - Process synchronously during upload</li>
</ul>
<p>The <code>:immediately</code> option has an optimization. During upload, the file is still in local memory:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/models/active_storage/attachment.rb</span>
<span class="k">def</span> <span class="nf">process_immediate_variants_from_io</span><span class="p">(</span><span class="n">io</span><span class="p">)</span>
  <span class="n">named_variants</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">_name</span><span class="p">,</span> <span class="n">named_variant</span><span class="o">|</span>
    <span class="k">next</span> <span class="k">unless</span> <span class="n">named_variant</span><span class="o">.</span><span class="n">process</span><span class="p">(</span><span class="n">record</span><span class="p">)</span> <span class="o">==</span> <span class="ss">:immediately</span>

    <span class="n">blob</span><span class="o">.</span><span class="n">variant</span><span class="p">(</span><span class="n">named_variant</span><span class="o">.</span><span class="n">transformations</span><span class="p">)</span><span class="o">.</span><span class="n">process_from_io</span><span class="p">(</span><span class="n">io</span><span class="p">)</span>
    <span class="n">io</span><span class="o">.</span><span class="n">rewind</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Instead of downloading the blob from storage, it processes directly from the uploaded IO. This avoids a round-trip to your storage service.</p>
<h2 id="avoiding-n1-queries">Avoiding N+1 Queries</h2>
<p>When loading multiple records with variants, you can hit N+1 issues. Active Storage provides scopes to eager-load variant records:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Load all variant records for images</span>
<span class="no">Message</span><span class="o">.</span><span class="n">all</span><span class="o">.</span><span class="n">with_all_variant_records</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">message</span><span class="o">|</span>
  <span class="n">message</span><span class="o">.</span><span class="n">images</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">image</span><span class="o">|</span>
    <span class="n">image_tag</span> <span class="n">image</span><span class="o">.</span><span class="n">variant</span><span class="p">(</span><span class="ss">:thumb</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This preloads the <code>variant_records</code> association, preventing individual queries for each variant check.</p>
<p>Here's how I think about the variant system:</p>
<pre data-language="text"><code class="code-inline language-text">┌─────────────────────────────────────────────────────────────────┐
│                        Your Model                               │
│  has_one_attached :avatar, variants: { thumb: {...} }           │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                       Attachment                                │
│  Resolves :thumb to transformation hash                         │
│  Delegates to blob.variant(transformations)                     │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                          Blob                                   │
│  Creates Variant or VariantWithRecord                           │
│  Wraps transformations in Variation                             │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    Variant(WithRecord)                          │
│  Generates unique storage key                                   │
│  Lazy processing via .processed                                 │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                        Variation                                │
│  Encodes transformations for URL                                │
│  Delegates to Transformer for processing                        │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Transformer                                │
│  Vips or ImageMagick via image_processing gem                   │
│  Validates operations, produces output file                     │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    Storage Service                              │
│  Variant stored at: variants/{blob_key}/{variation_hash}        │
│  Served via Redirect or Proxy controller                        │
└─────────────────────────────────────────────────────────────────┘</code></pre>
<p>Each module takes care of a specific thing:</p>
<ul>
<li><strong>Variant</strong> knows about storage keys and existence</li>
<li><strong>Variation</strong> knows about transformations and encoding</li>
<li><strong>Transformer</strong> knows about image processing</li>
<li><strong>Controllers</strong> know about HTTP serving</li>
</ul>
<h2 id="important-to-remember">Important to Remember</h2>
<ol>
<li><strong>Variants are lazy by default.</strong> No processing happens until the URL is first requested. Use <code>preprocessed: true</code> for high-traffic images.</li>
<li><strong>Variant URLs are signed.</strong> The transformation parameters are encoded using <code>MessageVerifier</code>, preventing tampering.</li>
<li><strong>Variant storage keys are deterministic.</strong> The same blob with the same transformations always produces the same key. Changing transformations changes the key (and URL).</li>
<li><strong><code>track_variants</code></strong> <strong>enables database tracking.</strong> This replaces service existence checks with database queries and enables variant management features.</li>
<li><strong>The first request pays the processing cost.</strong> Either accept this latency or preprocess variants. There's no free lunch.</li>
<li><strong>Transformers validate operations.</strong> Don't pass user input directly to variant methods.</li>
</ol>
<p>We'll cover following topics in future posts:</p>
<ul>
<li><strong>Previews</strong> work similarly to variants but for non-image files (PDFs, videos). Check <code>app/models/active_storage/preview.rb</code>.</li>
<li><strong>Representations</strong> unify variants and previews under a common interface. The <code>representation</code> method chooses the right approach based on content type.</li>
<li><strong>Service URLs</strong> have configurable expiration. See <code>ActiveStorage.service_urls_expire_in</code> and how it affects caching strategies.</li>
</ul>
<p>That covers the variant system. The next time you call <code>variant(:thumb)</code>, you'll know exactly what's happening under the hood.</p>
<hr>
<p><em>This post is part of a series on Active Storage internals. See also:</em> <a href="https://writesoftwarewell.com/active-storage-domain-model-blobs-attachments"><em>Understanding the Active Storage Domain Model</em></a> <em>and</em> <a href="https://writesoftwarewell.com/active-storage-has-one-attached-internals-dsl"><em>Understanding has_one_attached</em></a><em>.</em></p>

</div>
]]></content:encoded><pubDate>Fri, 16 Jan 2026 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/transform-images-with-activestorage-variants-rails</link><guid isPermaLink="true">https://writesoftwarewell.com/transform-images-with-activestorage-variants-rails</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>You Can Now Access Bearer Tokens Directly from Request</title><description>The&amp;nbsp;new bearer_token&amp;nbsp;method on the Request object is a nice addition to Rails. It removes boilerplate code and simplifies bearer token extraction. All Rails apps can now access bearer tokens the same way without having to write custom token extraction logic every time and worrying about edge cases.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>Two days ago, Rails added a new feature that makes working with bearer tokens easier. Before, you had to parse the <code>Authorization</code> header to extract them. Now, there's a dedicated <code>bearer_token</code> method on the request object that handles this for you.</p>
<p>Link to the PR: <a href="https://github.com/rails/rails/pull/56474">Add <code>ActionDispatch::Request#bearer_token</code> to extract the bearer token</a></p>
<p>When building APIs that use bearer token authentication (OAuth 2.0 and JWT-based authentication), you typically receive tokens from the client in the <code>Authorization</code> header (or <code>X-HTTP_AUTHORIZATION</code> if you're using a proxy) with this format:</p>
<pre data-language="text"><code class="code-inline language-text">Authorization: Bearer &lt;token&gt;</code></pre>
<p>Before you'd extract the token by parsing the Authorization header manually, something like:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">current_token</span>
  <span class="n">auth_header</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="o">[</span><span class="s1">&#39;Authorization&#39;</span><span class="o">]</span>
  <span class="k">return</span> <span class="kp">nil</span> <span class="k">unless</span> <span class="n">auth_header</span>

  <span class="n">match</span> <span class="o">=</span> <span class="n">auth_header</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sr">/^Bearer (.+)$/</span><span class="p">)</span>
  <span class="n">match</span><span class="o">[</span><span class="mi">1</span><span class="o">]</span> <span class="k">if</span> <span class="n">match</span>
<span class="k">end</span></code></pre>
<p>Different variations of the above method appeared repeatedly across Rails applications, and each implementation might handle edge cases slightly differently.</p>
<p>Rails now provides a <code>bearer_token</code> method directly on the request object:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">show</span>
  <span class="n">token</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">bearer_token</span>
  <span class="c1"># Use the token to authenticate...</span>
<span class="k">end</span></code></pre>
<p>Here's the implementation. It uses a regex to extract the token from the authorization header:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">bearer_token</span>
  <span class="n">authorization</span><span class="o">.</span><span class="n">to_s</span><span class="o">[</span><span class="sr">/\ABearer (.+)\z/</span><span class="p">,</span> <span class="mi">1</span><span class="o">]</span>
<span class="k">end</span></code></pre>
<ul>
<li><code>\A</code> - Matches the start of the string</li>
<li><code>Bearer </code>- Matches the literal text &quot;Bearer &quot; (with a space)</li>
<li><code>(.+)</code> - Captures one or more characters (the actual token)</li>
<li><code>\z</code> - Matches the end of the string</li>
</ul>
<p>The <code>[..., 1]</code> syntax extracts the first capture group (the token itself).</p>
<p>Note that it uses the existing <code>authorization</code> method, which checks multiple possible header locations:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">authorization</span>
  <span class="n">get_header</span><span class="p">(</span><span class="s2">&#34;HTTP_AUTHORIZATION&#34;</span><span class="p">)</span>   <span class="o">||</span>
  <span class="n">get_header</span><span class="p">(</span><span class="s2">&#34;X-HTTP_AUTHORIZATION&#34;</span><span class="p">)</span> <span class="o">||</span>
  <span class="n">get_header</span><span class="p">(</span><span class="s2">&#34;X_HTTP_AUTHORIZATION&#34;</span><span class="p">)</span> <span class="o">||</span>
  <span class="n">get_header</span><span class="p">(</span><span class="s2">&#34;REDIRECT_X_HTTP_AUTHORIZATION&#34;</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<p>This is to ensure compatibility with various proxy and web servers that might use different header names.</p>
<blockquote>
<p>💡 This is why you should read Rails source code. I had no idea that such a method existed to fetch the HTTP authorization header.</p>
</blockquote>
<p>If you read the test cases, you'll notice that the implementation handles a bunch of edge cases:</p>
<ul>
<li>No Authorization Header</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">request</span><span class="o">.</span><span class="n">bearer_token</span> <span class="c1"># =&gt; nil</span></code></pre>
<ul>
<li>Non-Bearer Authentication</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Authorization: Basic dXNlcjpwYXNzd29yZA==</span>
<span class="n">request</span><span class="o">.</span><span class="n">bearer_token</span> <span class="c1"># =&gt; nil</span></code></pre>
<ul>
<li>Empty Authorization Header</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Authorization:</span>
<span class="n">request</span><span class="o">.</span><span class="n">bearer_token</span> <span class="c1"># =&gt; nil</span></code></pre>
<ul>
<li>Bearer with No Token</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Authorization: Bearer</span>
<span class="n">request</span><span class="o">.</span><span class="n">bearer_token</span> <span class="c1"># =&gt; nil</span></code></pre>
<ul>
<li>Proxy Headers</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># X-HTTP_AUTHORIZATION: Bearer my-secret-token</span>
<span class="n">request</span><span class="o">.</span><span class="n">bearer_token</span> <span class="c1"># =&gt; &#34;my-secret-token&#34;</span></code></pre>
<h3 id="example">Example</h3>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">ApiController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
  <span class="n">before_action</span> <span class="ss">:authenticate_with_token</span>

  <span class="kp">private</span>

  <span class="k">def</span> <span class="nf">authenticate_with_token</span>
    <span class="n">token</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">bearer_token</span>
    <span class="k">return</span> <span class="n">render</span> <span class="ss">json</span><span class="p">:</span> <span class="p">{</span> <span class="ss">error</span><span class="p">:</span> <span class="s1">&#39;Unauthorized&#39;</span> <span class="p">},</span> <span class="ss">status</span><span class="p">:</span> <span class="ss">:unauthorized</span> <span class="k">unless</span> <span class="n">token</span>

    <span class="vi">@current_user</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">find_by_api_token</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>
    <span class="n">render</span> <span class="ss">json</span><span class="p">:</span> <span class="p">{</span> <span class="ss">error</span><span class="p">:</span> <span class="s1">&#39;Invalid token&#39;</span> <span class="p">},</span> <span class="ss">status</span><span class="p">:</span> <span class="ss">:unauthorized</span> <span class="k">unless</span> <span class="vi">@current_user</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>The <code>bearer_token</code> API is a nice addition to Rails that standardizes bearer token extraction. All Rails apps can now extract them the same way without having to write custom token extraction logic every time and worrying about edge cases.</p>

</div>
]]></content:encoded><pubDate>Tue, 30 Dec 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/rails-access-bearer-token-from-request</link><guid isPermaLink="true">https://writesoftwarewell.com/rails-access-bearer-token-from-request</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Combined Credentials in Rails 8.2</title><description>Rails 8.2 adds support for combined credentials, a unified API that checks environment variables first, then falls back to encrypted credentials, with consistent behavior for nested keys, defaults, and error handling. It's also possible to use your own combined configuration.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>While going through recently merged PRs in Rails, I came across a new feature from DHH, that handles a common concern in app configuration: managing credentials across different configuration backends in a single, consistent manner. [<a href="https://github.com/rails/rails/pull/56404">Link to the PR</a>]</p>
<p>When you're going through the PR, I highly recommend you also read Jean's (<a href="https://github.com/byroot">byroot</a>) code review comments and how DHH addresses them (or not). I learned a bunch of interesting Ruby / Rails tidbits just from the back-and-forth between them.</p>
<p>Anyways, the new combined credentials system, accessible via <code>Rails.app.creds</code>, provides a unified API for accessing configuration values from both environment variables and encrypted credential files. In addition, you can create custom configuration if you want than just using environment variables or encrypted files.</p>
<h2 id="whats-the-problem">What's the Problem?</h2>
<p>Before looking at the new feature, let's try to understand what problem it's trying to solve. I'll admit, this is rather a nice-to-have than a pressing problem, but still a nice quality-of-life improvement nonetheless.</p>
<p>Rails has supported encrypted credentials for years, and most teams have also relied on environment variables for production secrets. So you typically store sensitive configuration in one of two places (or both):</p>
<ol>
<li><strong>Encrypted credentials files</strong> (<code>config/credentials.yml.enc</code>) for secrets that should be version-controlled.</li>
<li><strong>Environment variables</strong> for deployment-specific configuration and CI/CD pipelines.</li>
</ol>
<p>In practice, that split usually creates a few issues:</p>
<ul>
<li><strong>Environment-specific overrides</strong>: You might want to use encrypted credentials for most values but override specific ones via environment variables in certain deployments.</li>
<li><strong>Migration between storage methods</strong>: Moving a credential from the encrypted file to an environment variable (or vice versa) required code changes throughout the application. You cannot easily move a secret from one source to the other without touching application code.</li>
<li><strong>Mix and Match:</strong> You end up with two APIs in your code: <code>ENV.fetch(&quot;DATABASE_URL&quot;)</code> in some places, <code>Rails.application.credentials.dig(:database, :url)</code> in others.</li>
</ul>
<p>Again, these are not serious problems, and most teams can work around them just fine, without much trouble. Still, having a built-in framework solution is better than relying on conventions and discipline alone, and that is exactly what the combined credentials feature provides.</p>
<h2 id="combined-credentials">Combined Credentials</h2>
<p>The combined credentials feature solves these problems by providing a single, consistent interface that checks multiple configuration sources in a defined order.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Check ENV first, then encrypted credentials</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:database_url</span><span class="p">)</span>
<span class="c1"># Equivalent to: ENV.fetch(&#34;DATABASE_URL&#34;) || Rails.app.credentials.dig(:database_url)</span>

<span class="c1"># Nested keys work, too</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:aws</span><span class="p">,</span> <span class="ss">:access_key_id</span><span class="p">)</span>
<span class="c1"># Equivalent to: ENV.fetch(&#34;AWS__ACCESS_KEY_ID&#34;) || Rails.app.credentials.dig(:aws, :access_key_id)</span></code></pre>
<p>The system follows a clear precedence order: environment variables are checked first, followed by encrypted credentials. This allows environment variables to override encrypted credentials when needed, such as on the CI/CD servers.</p>
<p>You may have noticed that I used <code>Rails.app.credentials</code> instead of <code>Rails.application.credentials</code> because DHH also added <code>Rails.app</code> as an alias for <code>Rails.application</code> in a separate PR (<a href="https://github.com/rails/rails/pull/56403">link</a>).</p>
<h2 id="how-does-it-work">How does it work?</h2>
<p>The combined credentials system is built on three classes in ActiveSupport:</p>
<h4 id="activesupportenvconfiguration">ActiveSupport::EnvConfiguration</h4>
<p>This class provides an interface for accessing environment variables using symbol-based keys (which is a nice feature in and of itself 😃 ):</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Access ENV variables with symbol keys</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">envs</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:db_password</span><span class="p">)</span>  <span class="c1"># ENV.fetch(&#34;DB_PASSWORD&#34;)</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">envs</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:cache_host</span><span class="p">)</span>    <span class="c1"># ENV[&#34;CACHE_HOST&#34;]</span>

<span class="c1"># Nested keys use double underscores</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">envs</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:aws</span><span class="p">,</span> <span class="ss">:region</span><span class="p">)</span> <span class="c1"># ENV.fetch(&#34;AWS__REGION&#34;)</span></code></pre>
<p>The <code>EnvConfiguration</code> class automatically converts symbol keys to uppercase strings and joins nested keys with double underscores, following a simple naming convention.</p>
<h4 id="activesupportencryptedconfiguration">ActiveSupport::EncryptedConfiguration</h4>
<p>This class already existed but now provides the same <code>require</code> and <code>option</code> methods as <code>EnvConfiguration</code>:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Consistent API with environment configuration</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">credentials</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:secret_key_base</span><span class="p">)</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">credentials</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:smtp_password</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="s2">&#34;fallback&#34;</span><span class="p">)</span></code></pre>
<h4 id="activesupportcombinedconfiguration">ActiveSupport::CombinedConfiguration</h4>
<p>This class ties everything together. It accepts multiple configuration backends and queries them in order:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># The default setup</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span> <span class="o">=</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">CombinedConfiguration</span><span class="o">.</span><span class="n">new</span><span class="p">(</span>
  <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">envs</span><span class="p">,</span>        <span class="c1"># Check ENV first</span>
  <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">credentials</span>  <span class="c1"># Then check encrypted credentials</span>
<span class="p">)</span></code></pre>
<h2 id="api-reference">API Reference</h2>
<p>The combined credentials system provides two primary methods:</p>
<ul>
<li><code>require(*keys)</code></li>
</ul>
<p>Returns the value for the specified key(s) or raises a <code>KeyError</code> if not found:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Single key</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:database_url</span><span class="p">)</span>

<span class="c1"># Nested keys</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:redis</span><span class="p">,</span> <span class="ss">:url</span><span class="p">)</span>

<span class="c1"># Raises KeyError if not found in any backend</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:nonexistent_key</span><span class="p">)</span> <span class="c1"># =&gt; KeyError</span></code></pre>
<ul>
<li><code>option(*keys, default: nil)</code></li>
</ul>
<p>Returns the value for the specified key(s) or the default value if not found:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Returns nil if not found</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:optional_feature_flag</span><span class="p">)</span>

<span class="c1"># Returns default value if not found</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:max_connections</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="mi">10</span><span class="p">)</span>

<span class="c1"># Default can be a callable</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:cache_ttl</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="mi">1</span><span class="o">.</span><span class="n">hour</span> <span class="p">})</span></code></pre>
<h3 id="examples">Examples</h3>
<ul>
<li>Database credentials</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Before: Inconsistent approaches</span>
<span class="n">database_url</span> <span class="o">=</span> <span class="no">ENV</span><span class="o">[</span><span class="s2">&#34;DATABASE_URL&#34;</span><span class="o">]</span> <span class="o">||</span> <span class="no">Rails</span><span class="o">.</span><span class="n">application</span><span class="o">.</span><span class="n">credentials</span><span class="o">.</span><span class="n">database_url</span>
<span class="n">redis_url</span> <span class="o">=</span> <span class="no">ENV</span><span class="o">.</span><span class="n">fetch</span><span class="p">(</span><span class="s2">&#34;REDIS_URL&#34;</span><span class="p">)</span> <span class="p">{</span> <span class="no">Rails</span><span class="o">.</span><span class="n">application</span><span class="o">.</span><span class="n">credentials</span><span class="o">.</span><span class="n">dig</span><span class="p">(</span><span class="ss">:redis</span><span class="p">,</span> <span class="ss">:url</span><span class="p">)</span> <span class="p">}</span>

<span class="c1"># After: Consistent interface</span>
<span class="c1"># ENV.fetch(&#34;DATABASE_URL&#34;) || Rails.app.credentials.database_url</span>
<span class="n">database_url</span> <span class="o">=</span> <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:database_url</span><span class="p">)</span>
<span class="c1"># ENV.fetch(&#34;REDIS__URL&#34;) || Rails.app.credentials.dig(:redis, :url)</span>
<span class="n">redis_url</span> <span class="o">=</span> <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:redis</span><span class="p">,</span> <span class="ss">:url</span><span class="p">)</span></code></pre>
<ul>
<li>Configure external services with fallback defaults:</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># AWS configuration with environment override capability</span>
<span class="n">aws_region</span> <span class="o">=</span> <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:aws</span><span class="p">,</span> <span class="ss">:region</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="s2">&#34;us-east-1&#34;</span><span class="p">)</span>
<span class="n">aws_access_key</span> <span class="o">=</span> <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:aws</span><span class="p">,</span> <span class="ss">:access_key_id</span><span class="p">)</span>

<span class="c1"># Stripe configuration</span>
<span class="n">stripe_key</span> <span class="o">=</span> <span class="k">if</span> <span class="no">Rails</span><span class="o">.</span><span class="n">env</span><span class="o">.</span><span class="n">production?</span>
  <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:stripe</span><span class="p">,</span> <span class="ss">:live_secret_key</span><span class="p">)</span>
<span class="k">else</span>
  <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:stripe</span><span class="p">,</span> <span class="ss">:test_secret_key</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<ul>
<li>Handle optional configuration gracefully:</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Feature flags with defaults</span>
<span class="n">enable_analytics</span> <span class="o">=</span> <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:features</span><span class="p">,</span> <span class="ss">:analytics</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="kp">false</span><span class="p">)</span>
<span class="n">max_file_size</span> <span class="o">=</span> <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">option</span><span class="p">(</span><span class="ss">:uploads</span><span class="p">,</span> <span class="ss">:max_size</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="mi">10</span><span class="o">.</span><span class="n">megabytes</span><span class="p">)</span></code></pre>
<h2 id="environment-variable-naming-convention">Environment Variable Naming Convention</h2>
<p>The system uses a specific convention for mapping nested keys to environment variables:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Symbol keys are converted to uppercase</span>
<span class="ss">:database_url</span> <span class="err">→</span> <span class="s2">&#34;DATABASE_URL&#34;</span>

<span class="c1"># Nested keys use double underscores</span>
<span class="o">[</span><span class="ss">:aws</span><span class="p">,</span> <span class="ss">:access_key_id</span><span class="o">]</span> <span class="err">→</span> <span class="s2">&#34;AWS__ACCESS_KEY_ID&#34;</span>
<span class="o">[</span><span class="ss">:redis</span><span class="p">,</span> <span class="ss">:cache</span><span class="p">,</span> <span class="ss">:ttl</span><span class="o">]</span> <span class="err">→</span> <span class="s2">&#34;REDIS__CACHE__TTL&#34;</span></code></pre>
<p>Nice to have a clear naming convention for environment variables.</p>
<h2 id="advanced-usage-custom-configuration-backends">Advanced Usage: Custom Configuration Backends</h2>
<p>If you want, you can create custom configuration backends, which lets you use external secret management systems:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># Example: Adding a custom backend</span>
<span class="k">class</span> <span class="nc">OnePasswordConfiguration</span>
  <span class="k">def</span> <span class="nf">require</span><span class="p">(</span><span class="o">*</span><span class="n">key</span><span class="p">)</span>
    <span class="c1"># Implement your custom logic here</span>
    <span class="c1"># Raise error if key not found</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">option</span><span class="p">(</span><span class="o">*</span><span class="n">keys</span><span class="p">)</span>
    <span class="c1"># Implement your custom logic here</span>
    <span class="c1"># Return nil if key not found</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="c1"># Use custom backend between ENV and credentials</span>
<span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span> <span class="o">=</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">CombinedConfiguration</span><span class="o">.</span><span class="n">new</span><span class="p">(</span>
  <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">envs</span><span class="p">,</span>
  <span class="no">OnePasswordConfiguration</span><span class="o">.</span><span class="n">new</span><span class="p">,</span>
  <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">credentials</span>
<span class="p">)</span></code></pre>
<p>This allows integration with services like HashiCorp Vault, AWS Secrets Manager, or other secret management solutions.</p>
<p>A benefit of using combined credentials is that moving a credential from the encrypted file to an environment variable (or vice versa) no longer requires code changes:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># This code works regardless of where the credential is stored</span>
<span class="n">api_key</span> <span class="o">=</span> <span class="no">Rails</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">creds</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:external_api</span><span class="p">,</span> <span class="ss">:key</span><span class="p">)</span>

<span class="c1"># The credential can be in:</span>
<span class="c1"># 1. ENV[&#34;EXTERNAL_API__KEY&#34;]</span>
<span class="c1"># 2. Rails.application.credentials.external_api.key</span>
<span class="c1"># 3. Both (ENV takes precedence)</span></code></pre>
<p>As you can see, the API is predictable and intuitive, and it just reads nicely. It is a simple improvement that removes the friction you did not always realize you were carrying. By having encrypted credentials and environment variables under a single, consistent interface, while allowing you to define custom backends, it simplifies configuration, and it does so in a very Rails way.</p>
<p>Give it a try in your app 👍</p>

</div>
]]></content:encoded><pubDate>Mon, 22 Dec 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/rails-combined-credentials</link><guid isPermaLink="true">https://writesoftwarewell.com/rails-combined-credentials</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Active Storage Internals: How has_one_attached DSL Works</title><description>In this post, we'll explore the internals of has_one_attached method in Active Storage. It covers two interesting patterns, i.e. proxy and change objects. We'll trace the control flow from the model DSL to persistence and uploads, and explain how files are created, detached, and purged.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>People usually read fiction before going to bed. I have a strange habit of reading the Rails source code at night. Not because it puts me to sleep, but for some reason I find the process of opening the Rails codebase, picking some feature, and just reading Ruby for an hour or two strangely calming. It lets me forget everything and just get in the flow for a few hours.</p>
<p>Anyways, after I published the post on <a href="https://writesoftwarewell.com/active-storage-domain-model-blobs-attachments">Active Storage Domain Model</a>, I stayed up until 2 am last night reading the Active Storage codebase to figure out how the <code>has_one_attached</code> method worked. It uses a couple of interesting patterns, and thought I'd share everything I learned. So since it's a rainy Saturday, I've been writing since morning, and what follows is my current understanding of how a single document gets attached to a Rails model. There might be gaps in my understanding, so please let me know if you find any mistakes.</p>
<p>This post explores the internals of Active Storage for the <code>has_one_attached</code> API. We’ll trace the path from the DSL on your model, through the proxy object, into the “change objects” that coordinate persistence and uploads, and finally into purge/detach behavior and background jobs. We'll stick to <code>has_one_attached</code> in this post, and cover <code>has_many_attached</code> in a future post.</p>
<p>I hope that you'll have the Rails source code open on the side while reading the post for browsing surrounding code, more context and better understanding. Otherwise, most of the post won't make any sense and you'll give up halfway. You've been warned.</p>
<p>Here're a couple of tips that I've found useful when <a href="https://writesoftwarewell.com/how-to-read-rails-codebase">reading the Rails source code</a>.</p>
<h2 id="the-model-dsl-code-generation-and-lifecycle">The Model DSL: Code Generation and Lifecycle</h2>
<p>As you already know, the <code>has_one_attached</code> API specifies the association between a 'single' file attachment and the Rails model. In the following example, we're declaring that a user can have an avatar attached to it.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">has_one_attached</span> <span class="ss">:avatar</span>
<span class="k">end</span></code></pre>
<p>As with many things in Rails (<a href="https://rubyonrails.org/doctrine#provide-sharp-knives">see: sharp knives</a>), this one line is very powerful. Declaring <code>has_one_attached :avatar</code> adds following capabilities to the <code>User</code> model:</p>
<ul>
<li>Associations: <code>avatar_attachment</code>, <code>avatar_blob</code></li>
<li>A reader: <code>avatar</code> returns a proxy (<code>ActiveStorage::Attached::One</code>)</li>
<li>A writer: <code>avatar=</code> records a “change” object (<code>ActiveStorage::Attached::Changes::CreateOne</code>) for later persistence/upload</li>
<li>Lifecycle callbacks:
<ul>
<li><code>after_save</code> to persist attachment and blob in the database</li>
<li><code>after_commit</code> to upload the actual file to the storage service (S3, GCS, etc.)</li>
</ul>
</li>
</ul>
<p>Highly recommend taking some time to read the <a href="https://github.com/rails/rails/blob/529f933fc8b13114d308dd0752f76a9e293c8537/activestorage/lib/active_storage/attached/model.rb#L108">source code</a> for this method. Key design decisions include:</p>
<ul>
<li>The writer does not immediately touch the database or upload files. It records an intent (<code>attachment_changes[name] = CreateOne/DeleteOne</code>) to be materialized by callbacks.</li>
<li>Persistence (association rows) is handled in the transaction (<code>after_save</code>).</li>
<li>Uploads happen only after the transaction commits (<code>after_commit</code>). This prevents orphaned uploads if the DB transaction rolls back.</li>
</ul>
<h3 id="side-note-whatre-generated-associations-methods">Side Note: What're Generated Associations Methods?</h3>
<p>You'll see a strange method named <code>generated_association_methods</code> in the above method.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">has_one_attached</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="ss">dependent</span><span class="p">:</span> <span class="ss">:purge_later</span><span class="p">,</span> <span class="ss">service</span><span class="p">:</span> <span class="kp">nil</span><span class="p">,</span> <span class="ss">strict_loading</span><span class="p">:</span> <span class="kp">false</span><span class="p">)</span>
  <span class="n">generated_association_methods</span><span class="o">.</span><span class="n">class_eval</span> <span class="s">&lt;&lt;-CODE, __FILE__, __LINE__ + 1
</span>    <span class="k">def</span> <span class="c1">#{name}</span>
      <span class="c1"># ...</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="c1">#{name}=(attachable)</span>
      <span class="c1"># ...</span>
    <span class="k">end</span>
  <span class="no">CODE</span>
<span class="k">end</span></code></pre>
<p>It's an <strong>internal core API in Active Record.</strong> It stores all the dynamically defined methods Rails creates for your model’s associations. It’s not something you usually call directly, but understanding what it does is helpful if you’re digging into Rails internals or metaprogramming.</p>
<p>Every time you define a new association, Rails defines its helper methods <strong>inside this module</strong> instead of directly on the model. Because the module is included into the model class, the methods still behave as if they were defined on the class itself.</p>
<p>Try this in your Rails app:</p>
<pre data-language="bash"><code class="code-inline language-bash">Post.generated_association_methods.instance_methods
app<span class="o">(</span>dev<span class="o">)</span>:002&gt;
<span class="o">=</span>&gt; <span class="o">[</span>:tagged_post_ids, :tagged_posts<span class="o">=</span>, :tagged_post_ids<span class="o">=</span>, :tag_ids, :tag_ids<span class="o">=</span>, :tagged_posts, :uploaded_images, :tags<span class="o">=</span>, :uploaded_image_ids, :tags, :uploaded_image_ids<span class="o">=</span>, :uploaded_images<span class="o">=]</span></code></pre>
<p>Okay, let's carry on with our code reading.</p>
<h2 id="the-proxy-object">The Proxy Object</h2>
<blockquote>
<p>Proxy means “a figure that can be used to represent something else”. The proxy design pattern is used to create a wrapper to cover the main object’s complexity from the client.</p>
</blockquote>
<p>Here's the reader method that was added on the model. The reader returns a proxy instance (<code>ActiveStorage::Attached::One</code>).</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="c1">#{name}</span>
  <span class="vi">@active_storage_attached</span> <span class="o">||=</span> <span class="p">{}</span>
  <span class="vi">@active_storage_attached</span><span class="o">[</span><span class="p">:</span><span class="c1">#{name}] ||= ActiveStorage::Attached::One.new(&#34;#{name}&#34;, self)</span>
<span class="k">end</span></code></pre>
<p>For the call <code>has_one_attached :avatar</code>, this translates to:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="k">def</span> <span class="nf">avatar</span>
    <span class="vi">@active_storage_attached</span> <span class="o">||=</span> <span class="p">{}</span>
    <span class="vi">@active_storage_attached</span><span class="o">[</span><span class="ss">:avatar</span><span class="o">]</span> <span class="o">||=</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Attached</span><span class="o">::</span><span class="no">One</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;avatar&#34;</span><span class="p">,</span> <span class="nb">self</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Basically, it creates a hash and inserts the proxy object for the <code>avatar</code> name and returns it for subsequent read calls.</p>
<p>The proxy object <code>Attached::One</code> has a simple API:</p>
<ul>
<li><code>attach(attachable)</code> attaches an attachable to the record (returns the attachment or <code>nil</code> depending on record validity)</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">attach</span><span class="p">(</span><span class="n">attachable</span><span class="p">)</span>
  <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">=&#34;</span><span class="p">,</span> <span class="n">attachable</span><span class="p">)</span>
  <span class="k">if</span> <span class="n">record</span><span class="o">.</span><span class="n">persisted?</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">record</span><span class="o">.</span><span class="n">changed?</span>
    <span class="k">return</span> <span class="k">if</span> <span class="o">!</span><span class="n">record</span><span class="o">.</span><span class="n">save</span>
  <span class="k">end</span>
  <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<p>Note that if the record is persisted and unchanged, <code>attach</code> triggers a synchronous <code>save</code>; otherwise attachment persistence is deferred to the next save. It returns the attachment proxy. If <code>save</code> fails, it returns <code>nil</code>.</p>
<ul>
<li><code>attachment</code> returns the underlying attachment, but you don't really have to use this as all the attachment methods are available on the model.</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">attachment</span>
  <span class="n">change</span><span class="o">.</span><span class="n">present?</span> <span class="p">?</span> <span class="n">change</span><span class="o">.</span><span class="n">attachment</span> <span class="p">:</span> <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">_attachment&#34;</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<ul>
<li><code>attached?</code> returns <code>true</code> if an attachment has been made.</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">attached?</span>
  <span class="n">attachment</span><span class="o">.</span><span class="n">present?</span>
<span class="k">end</span></code></pre>
<ul>
<li><code>purge</code>, <code>purge_later</code>, <code>detach</code> are delegated to the underlying “change” objects</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">delegate</span> <span class="ss">:purge</span><span class="p">,</span> <span class="ss">to</span><span class="p">:</span> <span class="ss">:purge_one</span>
<span class="n">delegate</span> <span class="ss">:purge_later</span><span class="p">,</span> <span class="ss">to</span><span class="p">:</span> <span class="ss">:purge_one</span>
<span class="n">delegate</span> <span class="ss">:detach</span><span class="p">,</span> <span class="ss">to</span><span class="p">:</span> <span class="ss">:detach_one</span>

<span class="kp">private</span>
  <span class="k">def</span> <span class="nf">purge_one</span>
    <span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">PurgeOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">record</span><span class="p">,</span> <span class="n">attachment</span><span class="p">)</span>
  <span class="k">end</span>
  
  <span class="k">def</span> <span class="nf">detach_one</span>
    <span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">DetachOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">record</span><span class="p">,</span> <span class="n">attachment</span><span class="p">)</span>
  <span class="k">end</span></code></pre>
<p>This change object pattern is quite interesting, so let's explore it.</p>
<h2 id="change-objects-encapsulate-attachdetachpurge-behavior">Change objects Encapsulate attach/detach/purge Behavior</h2>
<p>The <code>has_one_attached</code> method added a writer method on the model.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="c1">#{name}=(attachable)</span>
    <span class="n">attachment_changes</span><span class="o">[</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span><span class="o">]</span> <span class="o">=</span>
      <span class="k">if</span> <span class="n">attachable</span><span class="o">.</span><span class="n">nil?</span> <span class="o">||</span> <span class="n">attachable</span> <span class="o">==</span> <span class="s2">&#34;&#34;</span>
        <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">DeleteOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">,</span> <span class="nb">self</span><span class="p">)</span>
      <span class="k">else</span>
        <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">CreateOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">,</span> <span class="nb">self</span><span class="p">,</span> <span class="n">attachable</span><span class="p">)</span>
      <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>For the <code>has_one_attached :avatar</code>, this translates to:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">avatar</span><span class="o">=</span>
    <span class="n">attachment_changes</span><span class="o">[</span><span class="s2">&#34;avatar&#34;</span><span class="o">]</span> <span class="o">=</span> 
      <span class="k">if</span> <span class="n">attachable</span><span class="o">.</span><span class="n">nil?</span> <span class="o">||</span> <span class="n">attachable</span> <span class="o">==</span> <span class="s2">&#34;&#34;</span>
        <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">DeleteOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;avatar&#34;</span><span class="p">,</span> <span class="nb">self</span><span class="p">)</span>
      <span class="k">else</span>
        <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">CreateOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;avatar&#34;</span><span class="p">,</span> <span class="nb">self</span><span class="p">,</span> <span class="n">attachable</span><span class="p">)</span>
      <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This method builds one of two “change” objects depending on what you assign.</p>
<ol>
<li>When you do <code>user.avatar = attachable</code>, or <code>user.avatar.attach(attachable)</code>, Rails stores that assignment in the <code>attachment_changes</code> hash with <code>&quot;avatar&quot;</code> as the key and a <code>CreateOne</code> proxy as the value.</li>
<li>If instead you assign <code>nil</code> or an empty string (<code>&quot;&quot;</code>), Rails stores a <code>DeleteOne</code> proxy under the same key.</li>
</ol>
<p>This change object is then used later in the save cycle to actually create or remove the attachment.</p>
<p>The change objects implement the following responsibilities:</p>
<ul>
<li>Build or find a blob (<code>CreateOne</code>)</li>
<li>Build an attachment row (in-memory)</li>
<li>Persist association rows on <code>after_save</code>, upload on <code>after_commit</code></li>
<li>Reset local state for detach/purge</li>
</ul>
<h3 id="createone-attach">CreateOne (attach)</h3>
<p>The constructor eagerly identifies the blob content (without saving) to fill content type, byte size, checksum:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">record</span><span class="p">,</span> <span class="n">attachable</span><span class="p">)</span>
  <span class="vi">@name</span><span class="p">,</span> <span class="vi">@record</span><span class="p">,</span> <span class="vi">@attachable</span> <span class="o">=</span> <span class="nb">name</span><span class="p">,</span> <span class="n">record</span><span class="p">,</span> <span class="n">attachable</span>
  <span class="n">blob</span><span class="o">.</span><span class="n">identify_without_saving</span>
<span class="k">end</span></code></pre>
<p>The attachable can be one of the following:</p>
<ul>
<li><code>ActiveStorage::Blob</code>: Instance of a blob</li>
<li><code>ActionDispatch::Http::UploadedFile</code>: A user-uploaded file (most common)</li>
<li><code>Rack::Test::UploadedFile</code>: Convenient File for testing</li>
<li><code>Hash</code>: Data containing at least an open IO object and a filename</li>
<li><code>String</code>: Signed ID of a blob. Useful for direct uploads where the client-side needs to refer to the blob that was created ahead of the upload itself on form submission.</li>
</ul>
<h2 id="hooks-to-save-and-upload-files">Hooks to Save and Upload Files</h2>
<p>When the record is finally saved, the <code>after_save</code> callback calls the <code>save</code> method on the <code>CreateOne</code> change object to persist the attachment and the blob in the database (the file is not uploaded yet!).</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># model.rb</span>
<span class="n">after_save</span> <span class="p">{</span> <span class="n">attachment_changes</span><span class="o">[</span><span class="nb">name</span><span class="o">.</span><span class="n">to_s</span><span class="o">]&amp;.</span><span class="n">save</span> <span class="p">}</span>

<span class="c1"># create_one.rb</span>
<span class="k">def</span> <span class="nf">save</span>
  <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">_attachment=&#34;</span><span class="p">,</span> <span class="n">attachment</span><span class="p">)</span>
  <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">_blob=&#34;</span><span class="p">,</span> <span class="n">blob</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<p>…and the binary upload happens only after commit:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># model.rb</span>
<span class="n">after_commit</span><span class="p">(</span><span class="ss">on</span><span class="p">:</span> <span class="o">%</span><span class="n">i</span><span class="o">[</span> <span class="n">create</span> <span class="n">update</span> <span class="o">]</span><span class="p">)</span> <span class="p">{</span> <span class="n">attachment_changes</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="nb">name</span><span class="o">.</span><span class="n">to_s</span><span class="p">)</span><span class="o">.</span><span class="n">try</span><span class="p">(</span><span class="ss">:upload</span><span class="p">)</span> <span class="p">}</span>

<span class="c1"># create_one.rb</span>
<span class="k">def</span> <span class="nf">upload</span>
    <span class="c1"># ...</span>
<span class="k">end</span></code></pre>
<h2 id="blob-creation-identification-and-upload">Blob Creation, Identification, and Upload</h2>
<p>In blob construction, you need to understand the difference between two terms: <strong>“unfurl”</strong> vs <strong>“upload”</strong>:</p>
<ul>
<li>“Unfurl” computes checksum, sets <code>byte_size</code>, extracts/sets content type, and marks identified.</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># blob.rb</span>

<span class="k">def</span> <span class="nf">unfurl</span><span class="p">(</span><span class="n">io</span><span class="p">,</span> <span class="ss">identify</span><span class="p">:</span> <span class="kp">true</span><span class="p">)</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">checksum</span>     <span class="o">=</span> <span class="n">compute_checksum_in_chunks</span><span class="p">(</span><span class="n">io</span><span class="p">)</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">content_type</span> <span class="o">=</span> <span class="n">extract_content_type</span><span class="p">(</span><span class="n">io</span><span class="p">)</span> <span class="k">if</span> <span class="n">content_type</span><span class="o">.</span><span class="n">nil?</span> <span class="o">||</span> <span class="n">identify</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">byte_size</span>    <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">size</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">identified</span>   <span class="o">=</span> <span class="kp">true</span>
<span class="k">end</span></code></pre>
<ul>
<li>“Upload” sends bytes to the configured service and writes metadata headers. Normally, you do not have to call this method directly at all. Use the <code>create_and_upload</code> class method instead.</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">upload</span><span class="p">(</span><span class="n">io</span><span class="p">,</span> <span class="ss">identify</span><span class="p">:</span> <span class="kp">true</span><span class="p">)</span>
  <span class="n">unfurl</span> <span class="n">io</span><span class="p">,</span> <span class="ss">identify</span><span class="p">:</span> <span class="n">identify</span>
  <span class="n">upload_without_unfurling</span> <span class="n">io</span>
<span class="k">end</span></code></pre>
<p>Separating these steps enables the <code>CreateOne</code> flow:</p>
<ul>
<li>Identify/build the blob before saving (so validations, metadata, content type are available early)</li>
<li>Persist associations in-transaction</li>
<li>Upload only after commit</li>
</ul>
<p>This also allows the “don’t re-extract type” path by passing <code>identify: false</code>.</p>
<p>Now let's quickly explore how you delete / dis-associate the attachment and remove the file from the storage.</p>
<h3 id="delete-unset">Delete (unset)</h3>
<p>Writing <code>user.avatar = nil</code> or <code>&quot;&quot;</code> uses <code>DeleteOne</code>, which simply nulls the association at save-time. Remember the original setter method that was added by the <code>has_one_attached</code>.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># model.rb</span>
<span class="k">def</span> <span class="c1">#{name}=(attachable)</span>
  <span class="n">attachment_changes</span><span class="o">[</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span><span class="o">]</span> <span class="o">=</span>
    <span class="k">if</span> <span class="n">attachable</span><span class="o">.</span><span class="n">nil?</span> <span class="o">||</span> <span class="n">attachable</span> <span class="o">==</span> <span class="s2">&#34;&#34;</span>
      <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">DeleteOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">,</span> <span class="nb">self</span><span class="p">)</span>
    <span class="k">else</span>
      <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">CreateOne</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">,</span> <span class="nb">self</span><span class="p">,</span> <span class="n">attachable</span><span class="p">)</span>
    <span class="k">end</span>
<span class="k">end</span>

<span class="n">after_save</span> <span class="p">{</span> <span class="n">attachment_changes</span><span class="o">[</span><span class="nb">name</span><span class="o">.</span><span class="n">to_s</span><span class="o">]&amp;.</span><span class="n">save</span> <span class="p">}</span></code></pre>
<p><code>DeleteOne</code> is a simple change object. Here's the whole class. When the <code>user</code> record is saved, the callback will call the <code>DeleteOne#save</code> method, which sets the <code>avatar_attachment</code> association to <code>nil</code>.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># frozen_string_literal: true</span>

<span class="k">module</span> <span class="nn">ActiveStorage</span>
  <span class="k">class</span> <span class="nc">Attached</span><span class="o">::</span><span class="no">Changes</span><span class="o">::</span><span class="no">DeleteOne</span> <span class="c1"># :nodoc:</span>
    <span class="kp">attr_reader</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">:record</span>

    <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">record</span><span class="p">)</span>
      <span class="vi">@name</span><span class="p">,</span> <span class="vi">@record</span> <span class="o">=</span> <span class="nb">name</span><span class="p">,</span> <span class="n">record</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">attachment</span>
      <span class="kp">nil</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">save</span>
      <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">_attachment=&#34;</span><span class="p">,</span> <span class="kp">nil</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Whether the blob is purged upon replacing/removing depends on the <code>:dependent</code> option on the attachment reflection (default <code>:purge_later</code>; see below).</p>
<h3 id="detach">Detach</h3>
<p>“Detach” removes the attachment row but does not purge the blob. When you call <code>user.avatar.detach</code>, it's actually calling it on the <code>ActiveStorage::Attached::One</code> proxy object, which delegates it to the <code>Attached::Changes::DetachOne</code>. I leave the exercise of figuring out this flow as a challenge to the reader.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># detach_one.rb</span>

<span class="k">def</span> <span class="nf">detach</span>
  <span class="k">if</span> <span class="n">attachment</span><span class="o">.</span><span class="n">present?</span>
    <span class="n">attachment</span><span class="o">.</span><span class="n">delete</span>
    <span class="n">reset</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="k">def</span> <span class="nf">reset</span>
  <span class="n">record</span><span class="o">.</span><span class="n">attachment_changes</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
  <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">_attachment=&#34;</span><span class="p">,</span> <span class="kp">nil</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<p>The test suite documents the invariant: detach keeps the blob and object on the service:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="vi">@user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">detach</span>
<span class="n">assert_not</span> <span class="vi">@user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">attached?</span>
<span class="n">assert</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">exists?</span><span class="p">(</span><span class="n">blob</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
<span class="n">assert</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">service</span><span class="o">.</span><span class="n">exist?</span><span class="p">(</span><span class="n">blob</span><span class="o">.</span><span class="n">key</span><span class="p">)</span></code></pre>
<h3 id="purge-and-purge-later">Purge and Purge Later</h3>
<p>Purge will remove the actual file from the storage service. It will destroy the blob and attachment and then delete the file on the service.</p>
<p>For the one-attached proxy, <code>purge</code>/<code>purge_later</code> delegate to a change object that calls through to the <code>ActiveStorage::Attachment</code> API, then clears state. The flow (not behavior) works exactly like the <code>detach</code> method.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># purge_one.rb</span>

<span class="k">def</span> <span class="nf">purge</span>
  <span class="n">attachment</span><span class="o">&amp;.</span><span class="n">purge</span>
  <span class="n">reset</span>
<span class="k">end</span>

<span class="k">def</span> <span class="nf">purge_later</span>
  <span class="n">attachment</span><span class="o">&amp;.</span><span class="n">purge_later</span>
  <span class="n">reset</span>
<span class="k">end</span>

<span class="k">def</span> <span class="nf">reset</span>
  <span class="n">record</span><span class="o">.</span><span class="n">attachment_changes</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
  <span class="n">record</span><span class="o">.</span><span class="n">public_send</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">_attachment=&#34;</span><span class="p">,</span> <span class="kp">nil</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<p>The attachment model coordinates whether a blob should be purged when an attachment is destroyed, based on the <code>:dependent</code> option.</p>
<p>Purging ensures the blob (and remote object) are gone unless it’s shared:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="vi">@user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">purge</span>
<span class="n">assert_not</span> <span class="vi">@user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">attached?</span>
<span class="n">assert_not</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">exists?</span><span class="p">(</span><span class="n">blob</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
<span class="n">assert_not</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">service</span><span class="o">.</span><span class="n">exist?</span><span class="p">(</span><span class="n">blob</span><span class="o">.</span><span class="n">key</span><span class="p">)</span>

<span class="c1"># shared blob survives purge of one attachment</span>
<span class="vi">@user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">purge</span>
<span class="n">assert</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">exists?</span><span class="p">(</span><span class="n">blob</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
<span class="n">assert</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">service</span><span class="o">.</span><span class="n">exist?</span><span class="p">(</span><span class="n">blob</span><span class="o">.</span><span class="n">key</span><span class="p">)</span></code></pre>
<h2 id="my-mental-model-of-the-system">My Mental Model of the System</h2>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/5745nyjxdl77g6j7a13rw6l5xr90.webp" alt="has-one-attached-cover.webp" loading="lazy">
</figure><ul>
<li>Write to <code>record.avatar=</code> to stage a change (create or delete).</li>
<li>Save the record to persist attachment rows (in-transaction).</li>
<li>The actual upload happens after commit.</li>
<li>Use <code>record.avatar.attach(attachable)</code> most of the time, for immediate attach (with conditional save).</li>
<li>Use <code>detach</code> to drop the attachment row and leave the blob alone.</li>
<li>Use <code>purge</code>/<code>purge_later</code> to delete both the attachment and the blob (unless shared elsewhere).</li>
</ul>
<hr>
<p>That's a wrap. I hope you found this article helpful and you learned something new.</p>
<p>As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or <a href="mailto:akshay.khot@hey.com?ref=akshays-blog">send me an email</a>. I reply to all emails I get from developers, and I look forward to hearing from you.</p>
<p>If you'd like to receive future articles directly in your email, please <a href="https://writesoftwarewell.com/subscribe">subscribe to my blog</a>. Your email is respected, never shared, rented, sold or spammed. If you're already a subscriber, thank you.</p>

</div>
]]></content:encoded><pubDate>Sat, 18 Oct 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/active-storage-has-one-attached-internals-dsl</link><guid isPermaLink="true">https://writesoftwarewell.com/active-storage-has-one-attached-internals-dsl</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Active Storage Domain Model: Blobs and Attachments</title><description>Active Storage uses two main models: blobs and attachments. Blobs store the uploaded file's metadata and a link to the actual file, while attachments link those files to records. Understanding how they work together makes it easier to manage uploads, generate URLs, and process uploaded files.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>Active Storage is a wonderful library for managing file uploads in Rails. But terms like <em>blob</em> and <em>attachment</em> are easy to mix up, and that confusion can remain even after you’ve been using Active Storage regularly. I’ve run into that myself. I’ve used Active Storage for a long time in several projects, without ever really understanding how models, blobs and attachments worked together.</p>
<p>So I decided to read up and really understand the whole system, and what follows is my understanding of the Active Storage domain model. Once you understand their roles, it becomes easier to reason about file uploads, deletions, and reuse. This understanding is really useful as your app grows over time and you have to move, delete, or replace documents and the models they're attached to.</p>
<p>In this post, we'll only focus on the blobs and attachments for now, and explore variants in a later post, along with the other parts of Active Storage.</p>
<p>Here's the quick gist of it:</p>
<ul>
<li>A <strong>blob</strong> is the data about the uploaded file and a pointer to the actual file.</li>
<li>An <strong>attachment</strong> is “this <strong>record</strong> uses that <strong>file</strong> under this <strong>name</strong>.”</li>
</ul>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/sorxv688h6tdljeyzg5tza6cuccs.png" alt="active-storage-domain-model.png" loading="lazy">
  <figcaption class="attachment__caption">Active Storage Domain Model</figcaption>
</figure><h2 id="blob">Blob</h2>
<p>Represents metadata about the uploaded file. The actual file is stored in the storage service, such as AWS S3, disk, GCS, etc. The blob holds the metadata and the storage key for where that file resides on the service.</p>
<p><strong>Database Table:</strong> <code>active_storage_blobs</code></p>
<p><strong>Columns:</strong></p>
<ul>
<li><code>key</code> : the path/key used to fetch the bytes from the storage service</li>
<li><code>filename</code> : original filename</li>
<li><code>content_type</code> : MIME type of the file</li>
<li><code>byte_size</code> : Size of the file in number of bytes</li>
<li><code>checksum</code> : To check the integrity of the file</li>
<li><code>metadata</code> : JSON (image dimensions, analyzed flags, etc.)</li>
<li><code>service_name</code> : which storage service this blob lives on</li>
<li>Timestamps</li>
</ul>
<p>A blob is meant to represent a <strong>specific, unchanging file</strong>. Once a blob is created, it should always point to the same file data. That’s part of the design. Now you <em>can</em> update some of its descriptive information later (like metadata stored in the database), but you <strong>should never change the actual file it refers to</strong> or alter its storage key.</p>
<p>If you need to modify the file, for example, to create a resized version of an image, add a watermark, or replace it with a new upload, the right approach is to <strong>create a brand-new blob for the new file</strong> and, if the old one is no longer needed, <strong>purge (delete) the original blob</strong>.</p>
<p>This “immutability” makes blobs predictable and safe to reference throughout your app. You always know that a given blob refers to the exact same bytes it did when it was created.</p>
<h2 id="attachment">Attachment</h2>
<p>A polymorphic join table that connects a blob to your application model. An attachment belongs to a record and to a blob. A blob doesn't belong to a record. To get the blob from a record, you have to use the attachment.</p>
<p><code>Attachment</code> is the <strong>join</strong> row: it links <em>one</em> model record + a named slot (e.g. <code>&quot;avatar&quot;</code>, <code>&quot;photos&quot;</code>) to <em>one</em> <code>Blob</code>.</p>
<p>Check out the following post to learn more about polymorphic associations in Rails: <a href="https://writesoftwarewell.com/rails-polymorphic-associations-why-what-how">Polymorphic Associations in Rails: Why, What, and How</a></p>
<p><strong>Database table:</strong> <code>active_storage_attachments</code></p>
<p><strong>Columns:</strong></p>
<ul>
<li><code>name</code>: the association name on your model (<code>:avatar</code>, <code>:files</code>, …)</li>
<li><code>record_type</code> / <code>record_id</code>: which model/row is attached</li>
<li><code>blob_id</code>: which blob it’s pointing at</li>
<li>Timestamp</li>
</ul>
<p>Here's how they all work together.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/td2uqvz510f2rhn08g0x4w833l32.png" alt="active-storage-architecture.png" loading="lazy">
  <figcaption class="attachment__caption">Active Storage Architecture</figcaption>
</figure><p><strong>Important:</strong> Because attachments use a polymorphic <code>record_type</code> (class name string), if you rename or refactor the model (say from <code>User</code> → <code>AccountUser</code>), existing <code>active_storage_attachments</code> rows will still reference the old class name string. You’ll need a migration to update those rows.</p>
<p>Consider the following models in a Rails app.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">User</span>
  <span class="n">has_one_attached</span> <span class="ss">:avatar</span>
<span class="k">end</span>

<span class="k">class</span> <span class="nc">Project</span>
  <span class="n">has_many_attached</span> <span class="ss">:documents</span>
<span class="k">end</span></code></pre>
<p><code>has_one_attached :avatar</code> or <code>has_many_attached :documents</code> defines the attachment association.</p>
<p>When you do <code>user.avatar.attach(...)</code>, Active Storage does three things:</p>
<ol>
<li>Create a blob to represent that uploaded file and store its metadata</li>
<li>Upload the file to the storage service</li>
<li>Create an attachment that links the <code>user</code> model record to that blob.</li>
</ol>
<p><strong>Note:</strong> If the record is persisted and unchanged, the attachment is saved to the database immediately. Otherwise, it'll be saved to the DB when the record is next saved.</p>
<p>A blob can be attached multiple times (to same or different models - though I think it's not that common). This is how you reuse the underlying file without having to upload it again. Each usage creates a separate attachment row pointing to the same blob and the different records.</p>
<p><strong>Note:</strong> For direct uploads, Rails will create a blob by uploading the file directly to S3 from the client. The attachment is created later when the form is submitted. If the form is abandoned, you'll end up with unattached blobs, which can be cleared with the <code>active_storage:purge_unattached</code> task. We'll cover direct uploads in a future post, but wanted to mention this here.</p>
<p>In your app, you'll typically perform the following operations:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">user</span><span class="o">.</span><span class="n">avatar</span>                <span class="c1"># =&gt; returns an ActiveStorage::Attached::One proxy</span>
<span class="n">user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">attached?</span>      <span class="c1"># =&gt; true/false</span>
<span class="n">user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">attachment</span>     <span class="c1"># =&gt; the ActiveStorage::Attachment record (join)</span>
<span class="n">user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">blob</span>           <span class="c1"># =&gt; the ActiveStorage::Blob record (file metadata)</span>

<span class="n">user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">download</span>       <span class="c1"># =&gt; downloads the blob bytes into memory</span>
<span class="n">user</span><span class="o">.</span><span class="n">avatar</span><span class="o">.</span><span class="n">open</span> <span class="k">do</span> <span class="o">|</span><span class="n">file</span><span class="o">|</span> <span class="c1"># =&gt; opens a Tempfile with the blob content</span>
  <span class="c1"># do something with file.path, etc.</span>
<span class="k">end</span></code></pre>
<h3 id="replacing-and-deleting-things">Replacing and Deleting Things</h3>
<p>If you want to delete the attachment, i.e. the link between a record and a blob, without deleting the actual file, use the <code>detach</code> method on the model, i.e. <code>user.avatar.detach</code>. This will destroy the <code>Attachment</code> row while keeping the file as-is. If another record still uses that blob, it stays intact.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/cxrvtnspkz5m2xrzva7ozdshquud.png" alt="Detach Attachment.png" loading="lazy">
  <figcaption class="attachment__caption">Detach Attachment</figcaption>
</figure><p>If you want to delete both the attachment and the blob, use the <code>purge</code> method, e.g. <code>user.avatar.purge</code>. This will remove the actual file from the storage service. Remember: This will make a network call to the storage service. To do this in a background job, use the <code>purge_later</code> method instead.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/blyioz2m9adoy2cfykp8jyb75qx9.png" alt="purge-attachment.png" loading="lazy">
  <figcaption class="attachment__caption">Purge Attachment</figcaption>
</figure><h2 id="what-can-you-do-with-a-blob">What can you do with a Blob?</h2>
<p>Once you understand that a blob represents a specific uploaded file, the next question is: <em><strong>what can you actually do with it?</strong></em></p>
<p>It turns out <a href="https://api.rubyonrails.org/classes/ActiveStorage/Blob.html"><code>ActiveStorage::Blob</code></a> gives you a rich API to work with files in your Rails app. From reading metadata to downloading bytes, generating URLs, analyzing content, and even creating new blobs manually, all without ever touching the underlying storage service directly.</p>
<p>Here’s a practical tour of the most useful things you can do with a blob.</p>
<h3 id="1-generate-signed-urls-for-direct-access">1. Generate signed URLs for direct access</h3>
<p>One of the most common use cases is to give the browser a link to download or view the file. Rails can generate secure, expiring URLs:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">rails_blob_url</span><span class="p">(</span><span class="n">blob</span><span class="p">)</span>
<span class="c1"># =&gt; &#34;https://yourapp.com/rails/active_storage/blobs/.../profile.png&#34;</span></code></pre>
<p>Or, for inline display in an <code>&lt;img&gt;</code> tag:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="o">&lt;%=</span> <span class="n">image_tag</span> <span class="n">url_for</span><span class="p">(</span><span class="n">user</span><span class="o">.</span><span class="n">avatar</span><span class="p">)</span> <span class="o">%&gt;</span></code></pre>
<p>These URLs are <strong>signed</strong>, meaning they expire and can’t be guessed.</p>
<h3 id="2-access-metadata-about-the-file">2. Access metadata about the file</h3>
<p>Every blob stores details about the uploaded file. You can access these directly:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">blob</span> <span class="o">=</span> <span class="n">post</span><span class="o">.</span><span class="n">cover_image</span><span class="o">.</span><span class="n">blob</span>

<span class="n">blob</span><span class="o">.</span><span class="n">filename</span>      <span class="c1"># =&gt; #&lt;ActiveStorage::Filename &#34;autumn.jpg&#34;&gt;</span>
<span class="n">blob</span><span class="o">.</span><span class="n">content_type</span>  <span class="c1"># =&gt; &#34;image/jpeg&#34;</span>
<span class="n">blob</span><span class="o">.</span><span class="n">byte_size</span>     <span class="c1"># =&gt; 245183</span>
<span class="n">blob</span><span class="o">.</span><span class="n">checksum</span>      <span class="c1"># =&gt; &#34;Yf1K1Gk...==&#34;  # MD5 checksum of the content</span>
<span class="n">blob</span><span class="o">.</span><span class="n">metadata</span>      <span class="c1"># =&gt; { &#34;identified&#34; =&gt; true, &#34;width&#34; =&gt; 1200, &#34;height&#34; =&gt; 630 }</span>
<span class="n">blob</span><span class="o">.</span><span class="n">service_name</span>  <span class="c1"># =&gt; &#34;amazon&#34;</span></code></pre>
<p>This is useful when you need to display file info in the UI, validate content types, or log uploads.</p>
<h3 id="3-read-or-download-the-actual-file-data">3. Read or download the actual file data</h3>
<p>A blob is linked to a file in storage service, and you can access those bytes in several ways:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">blob</span><span class="o">.</span><span class="n">download</span>       <span class="c1"># =&gt; returns the entire file as a string (useful for small files)</span>

<span class="n">blob</span><span class="o">.</span><span class="n">open</span> <span class="k">do</span> <span class="o">|</span><span class="n">file</span><span class="o">|</span> <span class="c1"># =&gt; gives you a Tempfile to work with</span>
  <span class="nb">puts</span> <span class="n">file</span><span class="o">.</span><span class="n">path</span>
  <span class="c1"># do something with the file, e.g., send it to another service</span>
<span class="k">end</span></code></pre>
<p>You can also <strong>stream</strong> the data in chunks if the file is large. Each chunk is yielded to the block.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">blob</span><span class="o">.</span><span class="n">download</span> <span class="k">do</span> <span class="o">|</span><span class="n">chunk</span><span class="o">|</span>
  <span class="n">process</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>  <span class="c1"># handle data incrementally</span>
<span class="k">end</span></code></pre>
<h3 id="4-trigger-analysis-to-extract-metadata">4. Trigger analysis to extract metadata</h3>
<p>For certain file types (like images, videos, or PDFs), Active Storage can automatically extract metadata such as dimensions, duration, or page count.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">blob</span><span class="o">.</span><span class="n">analyze</span>
<span class="n">blob</span><span class="o">.</span><span class="n">analyzed?</span>      <span class="c1"># =&gt; true</span>
<span class="n">blob</span><span class="o">.</span><span class="n">metadata</span>       <span class="c1"># =&gt; { &#34;width&#34; =&gt; 800, &#34;height&#34; =&gt; 600, &#34;analyzed&#34; =&gt; true }</span></code></pre>
<h3 id="5-create-blobs-manually-for-scripts-or-background-jobs">5. Create blobs manually (for scripts or background jobs)</h3>
<p>You don’t always need to go through an <code>attach</code> call. It's fine to create blobs directly. This is useful in background tasks or service objects.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">blob</span> <span class="o">=</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">create_and_upload!</span><span class="p">(</span>
  <span class="ss">io</span><span class="p">:</span> <span class="no">File</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&#34;/path/to/report.pdf&#34;</span><span class="p">),</span>
  <span class="ss">filename</span><span class="p">:</span> <span class="s2">&#34;report.pdf&#34;</span><span class="p">,</span>
  <span class="ss">content_type</span><span class="p">:</span> <span class="s2">&#34;application/pdf&#34;</span>
<span class="p">)</span>

<span class="c1"># attach it later</span>
<span class="n">user</span><span class="o">.</span><span class="n">documents</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">blob</span><span class="p">)</span></code></pre>
<p>Or if you already have the file in memory:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">blob</span> <span class="o">=</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="o">.</span><span class="n">create_after_upload!</span><span class="p">(</span>
  <span class="ss">io</span><span class="p">:</span> <span class="no">StringIO</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">pdf_content</span><span class="p">),</span>
  <span class="ss">filename</span><span class="p">:</span> <span class="s2">&#34;generated.pdf&#34;</span><span class="p">,</span>
  <span class="ss">content_type</span><span class="p">:</span> <span class="s2">&#34;application/pdf&#34;</span>
<span class="p">)</span></code></pre>
<p>I hope this post was helpful in somewhat clarifying the Active Storage domain model. We'll continue with the other aspects of Active Storage in future posts.</p>

</div>
]]></content:encoded><pubDate>Thu, 16 Oct 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/active-storage-domain-model-blobs-attachments</link><guid isPermaLink="true">https://writesoftwarewell.com/active-storage-domain-model-blobs-attachments</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Rails on Localhost: Secure Context and Local HTTPS with Caddy</title><description>Localhost is treated as a trustworthy origin even without TLS, so all apps on localhost run in a secure context. This allows secure features to work in development. You can also run multiple apps on localhost with subdomains + ports to separate them. When you do need local HTTPS, use Caddy server.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p><strong>TL;DR:</strong> You can and should use localhost in development. Browsers give a special treatment to the <code>http://localhost</code> domain. Even though it's on HTTP, most of the time it will be treated as HTTPS. So any browser APIs that need HTTPS, will continue working even if you're using localhost. When you do need HTTPS locally, use Caddy.</p>
<p>Also, localhost can have subdomains. So you can just prefix the URL with your app name, and suffix it with the port to separate multiple apps, like <a href="http://%7Bsubdomain%7D.localhost:%7Bport%7D/"><code>http://{subdomain}.localhost:{port}</code></a>. I had no idea about this until I saw <a href="https://x.com/dhh/status/1938336493665403167">this tweet from DHH</a>.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/mt79oevzm4ex2djmdw2b6pu4g3yi.png" alt="dhh-localhost-tweet.png" loading="lazy">
  <figcaption class="attachment__caption">DHH localhost tweet</figcaption>
</figure><p>and again in the Rails World keynote...</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/uhzyz5xazes91wlr05777hyg63ws.png" alt="rails-world-keynote.png" loading="lazy">
  <figcaption class="attachment__caption">Rails World Keynote</figcaption>
</figure><h2 id="secure-contexts">Secure Contexts</h2>
<blockquote>
<p>A potentially trustworthy origin is one that the browser can generally trust to deliver data security, even though strictly speaking it does not meet the criteria of a secure context. - <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#potentially_trustworthy_origins">MDN</a></p>
</blockquote>
<p>Browsers normally only treat HTTPS origins as <em>secure contexts</em>. But there’s a special exception for local development: certain origins are treated as <em><strong>potentially trustworthy</strong></em> even if they don’t use TLS.</p>
<p>That list includes:</p>
<ul>
<li><code>http://127.0.0.1</code></li>
<li><code>http://localhost</code></li>
<li>Any subdomain ending in <code>.localhost</code> (e.g. <code>http://app.localhost</code>)</li>
</ul>
<p>The reasoning is simple: when you access these addresses, the request never leaves your machine. There’s no network hop where data could be intercepted. So, although it’s technically plain HTTP, the browser considers it safe enough to behave as if it were secure.</p>
<p>Using subdomains with <code>localhost</code> (like <code>blog.localhost:3000</code>) has several practical benefits for local development, especially when working on complex Rails apps. They make your development environment behave more like production, helping you test cookies, sessions, routing, and multi-app setups, without extra DNS or host configuration.</p>
<p>Here're a few use-cases for localhost domains with a custom subdomain.</p>
<h3 id="1simulating-production-like-domains">1. <strong>Simulating production-like domains</strong></h3>
<ul>
<li>In production, you might serve different parts of your app on different subdomains (e.g., <code>blog.example.com</code>, <code>api.example.com</code>).</li>
<li>Using <code>blog.localhost</code> mimics this locally, so you can test routing, cookies, CORS, and redirects in an environment closer to production.</li>
</ul>
<h3 id="2handling-cookies--sessions-correctly">2. <strong>Handling cookies &amp; sessions correctly</strong></h3>
<ul>
<li>Browsers scope cookies to a domain.</li>
<li>With subdomains (e.g., <code>blog.localhost</code>, <code>admin.localhost</code>), you can:
<ul>
<li>Test shared cookies across subdomains.</li>
<li>Verify session handling when different subdomains need to share authentication (like SSO).</li>
</ul>
</li>
</ul>
<h3 id="3testing-multi-tenant-or-subdomain-based-routing">3. <strong>Testing multi-tenant or subdomain-based routing</strong></h3>
<ul>
<li>Rails apps often use subdomain-based routing for multi-tenancy (<code>tenant1.example.com</code>, <code>tenant2.example.com</code>).</li>
<li>Using <code>tenant.localhost</code> allows you to test these routes without production domains.</li>
</ul>
<h3 id="4easier-separation-for-multiple-apps">4. <strong>Easier separation for multiple apps</strong></h3>
<ul>
<li>If you’re running multiple apps (e.g., <code>writesoftwarewell.localhost:3000</code>, <code>typeangle.localhost:3001</code>), subdomains help keep them organized and accessible.</li>
</ul>
<h3 id="5no-extra-setup-needed">5. <strong>No extra setup needed</strong></h3>
<ul>
<li><code>localhost</code> is a special-use domain that browsers resolve without DNS.</li>
<li>Any <code>*.localhost</code> automatically resolves to <code>127.0.0.1</code>. No <code>/etc/hosts</code> changes are required.</li>
</ul>
<hr>
<h2 id="what-if-i-do-need-local-https">What if I do need local HTTPS?</h2>
<p>There're some edge cases when you may want your local development app to behave very similar to the one in production, which may include <strong>using HTTPS during development.</strong> This is the case when you want to debug an issue that occurs on HTTPS but not on HTTP, or you want to locally test third-party APIs that need HTTPS.</p>
<p>You can run the Rails app locally on HTTPS with the Caddy server. <a href="https://caddyserver.com/docs/">Caddy</a> is an awesome web server to serve your sites, services, and applications.</p>
<p>First, install Caddy.</p>
<pre data-language="bash"><code class="code-inline language-bash">$ brew install caddy</code></pre>
<p>We have the Rails app running on the port 3000. We'll use Caddy to as a reverse proxy server that will accept requests over HTTPS and forward them to the Rails app. In Caddy, setting up a reverse proxy is as simple as this:</p>
<pre data-language="go"><code class="code-inline language-go"><span class="nx">blog</span><span class="p">.</span><span class="nx">localhost</span><span class="w"> </span><span class="p">{</span><span class="w">
</span><span class="w">	</span><span class="nx">reverse_proxy</span><span class="w"> </span><span class="p">:</span><span class="mi">3000</span><span class="w">
</span><span class="p">}</span></code></pre>
<p>Add the following code in a new file called <code>Caddyfile</code>, stored in your Rails app.</p>
<p>Now, you can run Caddy from your Rails app.</p>
<pre data-language="bash"><code class="code-inline language-bash">$ caddy run</code></pre>
<p>The <code>run</code> command starts Caddy in the foreground, i.e. you see the output. If you want to run it in the background, run the <code>caddy start</code> command. However, I suggest running it in the foreground.</p>
<p>In a separate terminal window / tab, launch the Rails server as usual.</p>
<pre data-language="bash"><code class="code-inline language-bash">$ rails server</code></pre>
<p>Now visit the url endpoint <code>https://blog.localhost</code>. The very first time, it will take a second to load as Caddy needs to generate a self-signed certificate for the <code>blog.localhost</code> domain. But you should quickly see your app running on HTTPS.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/d4dlt0b8h0uyp1u6jsefhsmnqzj9.png" alt="blog-localhost.png" loading="lazy">
  <figcaption class="attachment__caption">Blog localhost</figcaption>
</figure><p>We're almost done, but there is one small quality-of-life enhancement we can make. Right now, it's quite cumbersome having to run a separate commands to launch the Caddy server. Let's move the <code>caddy run</code> command in the <code>Procfile</code> to launch Caddy along with the Rails server and TailwindCSS compiler.</p>
<p>Here's the updated <code>Procfile.dev</code>:</p>
<pre data-language="text"><code class="code-inline language-text">web: bin/rails server
css: bin/rails tailwindcss:watch
caddy: caddy run</code></pre>
<p>That's it. Now you can run <code>bin/dev</code> to launch your application along with Caddy.</p>
<p>Visit <code>https://blog.localhost</code> to ensure the app is up and running and serving requests.</p>

</div>
]]></content:encoded><pubDate>Mon, 08 Sep 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/rails-localhost-secure-context-local-https-caddy</link><guid isPermaLink="true">https://writesoftwarewell.com/rails-localhost-secure-context-local-https-caddy</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Sitemaps: A Quick SEO Win for New Websites</title><description>A sitemap lists your site's pages, helping Google crawl it efficiently. It's especially useful for large sites or new sites with zero backlinks. This post shows how you can create one in your Rails site, how to add it to Google Search Console, and how to index new pages as soon as you publish them.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>I recently added sitemaps to a few Rails-based marketing sites I manage for clients, and within weeks, we saw a noticeable boost in search traffic. It reminded me that not many people know about them or have totally forgotten about them (it's quite an old but effective SEO technique). Even fewer know about Google Search Console (not Google Analytics), the official Google tool where you can submit sitemaps and request indexing for new pages as soon as you publish them.</p>
<p>So wanted to give a quick primer about what a sitemap is, how you can create it yourself in Rails, and how to submit it to Google. Sometimes it's these small technical things that can make a big difference.</p>
<p>SEO is all about helping search engines better understand your website's content, which helps your target readers find your website faster. If you're selling anything online, better SEO = more traffic to your website = more sales for whatever you're selling.</p>
<p>Most search engines like Google automatically crawl the Internet looking for new pages to add to their index. The thing is, there is not a single database of all the web pages in the world, so Google must constantly look for new pages to index them. Most often, Google discovers a website because another website that's already indexed links to a page from that website.</p>
<p>So the obvious next question is: <strong>how can a new website which doesn't have any external links can tell Google to index itself?</strong></p>
<p>Of course, you can use SEO agencies that spam reputed websites asking them to backlink to the new website, or ask to submit junk guest posts that link back to the website. I get probably dozens of such emails every week to get backlinks from this blog. Thanks to <a href="https://www.hey.com/features/the-screener/">HEY</a>, most of those emails go straight to spam, and I never even see them (not an ad, just a happy user and big fan).</p>
<p>Anyway, the most effective SEO approach that works is to play the long term game, and <strong>write content that people want to read.</strong> Write content that shows experience, expertise, authoritativeness, and builds trust, also known as E-E-A-T framework in SEO circles.</p>
<p>Here's the Google Console report for Write Software, Well for the past year. <strong>The wheels of SEO turn slowly, but they grind exceedingly fine.</strong></p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/n601ed990stxz354pv1wsrndfdv3.png" alt="wheels-of-seo.png" loading="lazy">
  <figcaption class="attachment__caption">Wheels of SEO</figcaption>
</figure><p><strong>Got it, but what about a new blog?</strong></p>
<p>When you start a new blog or a new marketing website for your company, there's one simple thing you can do to tell Google about which pages your site has so its crawlers can index them. <strong>Use</strong> <strong>a sitemap</strong>.</p>
<p><strong>What's a sitemap?</strong></p>
<p>A sitemap is an XML file that lists the pages, videos, documents and other files on your website and the relationships between them. It tells Google which pages to index and when they were last updated.</p>
<p><strong>Do I need a sitemap?</strong></p>
<p>Yes, you do. Although Google will discover most of the pages eventually, why wait? If your site is new, it won't have any external links to it. Google searches the web by crawling URLs found in previously crawled pages. Hence it might take too long if there're no pages linking to your site.</p>
<p><strong>I'm sold. How can I build a sitemap?</strong></p>
<p>Most likely, the platform you're using already generates the sitemap. For example, I've been using the excellent <a href="https://ghost.org/">Ghost</a> platform for the past three years to write this blog (again, not an ad, just a happy user). It automatically creates the sitemap based on the latest entries. You can check it out at <a href="https://writesoftwarewell.com/sitemap.xml">/sitemap.xml</a> (click the links to explore further). This is how it looks:</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/4zhjwde99dwbn0vl0zb46dco3lmc.png" alt="sitemap-for-write-software-well.png" loading="lazy">
  <figcaption class="attachment__caption">Sitemap for Write Software, Well Blog</figcaption>
</figure><p>If you have a custom-built CMS, check out the gems or libraries provided by your web framework. For example, in Rails you can use the <a href="https://github.com/kjvarga/sitemap_generator">sitemap_generator</a> gem. If you're using Jekyll, there's a <a href="https://github.com/jekyll/jekyll-sitemap">jekyll-sitemap</a> plugin, and so on. If you're the non-technical owner of the website, talk to your developers about building one.</p>
<p>I have built and maintain a few simple marketing websites with Rails for some of my clients, and have found it easier to just build the sitemap in plain Ruby. Here's a quick demo of how you can do it in Rails for a simple blog.</p>
<h2 id="how-to-generate-sitemap-in-rails">How to Generate Sitemap in Rails</h2>
<p>When creating a sitemap, you're essentially telling the crawlers about all the URLs on your site you want to show in the search results. Also note that these are the canonical URLs, i.e complete URLs and not paths.</p>
<p>First, you'll need a route for the <code>/sitemap.xml</code> endpoint.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">get</span> <span class="s2">&#34;sitemap&#34;</span><span class="p">,</span> <span class="ss">to</span><span class="p">:</span> <span class="s2">&#34;sitemap#index&#34;</span><span class="p">,</span> <span class="ss">defaults</span><span class="p">:</span> <span class="p">{</span> <span class="nb">format</span><span class="p">:</span> <span class="s2">&#34;xml&#34;</span> <span class="p">}</span></code></pre>
<p>Next, add the following <code>SitemapController</code>:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">SitemapController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
  <span class="c1"># GET /sitemap.xml</span>
  <span class="k">def</span> <span class="nf">index</span>
    <span class="c1"># Cache the sitemap for 1 hour</span>
    <span class="n">expires_in</span> <span class="mi">1</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="kp">public</span><span class="p">:</span> <span class="kp">true</span>

    <span class="vi">@posts</span> <span class="o">=</span> <span class="no">Post</span><span class="o">.</span><span class="n">published</span><span class="o">.</span><span class="n">includes</span><span class="p">(</span><span class="ss">:tags</span><span class="p">)</span><span class="o">.</span><span class="n">order</span><span class="p">(</span><span class="ss">published_on</span><span class="p">:</span> <span class="ss">:desc</span><span class="p">)</span>
    <span class="vi">@pages</span> <span class="o">=</span> <span class="no">Page</span><span class="o">.</span><span class="n">all</span><span class="o">.</span><span class="n">order</span><span class="p">(</span><span class="ss">:title</span><span class="p">)</span>
    <span class="vi">@tags</span> <span class="o">=</span> <span class="no">Tag</span><span class="o">.</span><span class="n">joins</span><span class="p">(</span><span class="ss">:posts</span><span class="p">)</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span><span class="no">Post</span><span class="o">.</span><span class="n">published</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="o">.</span><span class="n">order</span><span class="p">(</span><span class="ss">:name</span><span class="p">)</span>
    <span class="vi">@static_pages</span> <span class="o">=</span> <span class="n">static_pages_data</span>

    <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="nb">format</span><span class="o">|</span>
      <span class="nb">format</span><span class="o">.</span><span class="n">xml</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">layout</span><span class="p">:</span> <span class="kp">false</span><span class="p">,</span> <span class="ss">content_type</span><span class="p">:</span> <span class="s2">&#34;application/xml&#34;</span> <span class="p">}</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="kp">private</span>

  <span class="k">def</span> <span class="nf">static_pages_data</span>
    <span class="o">[</span>
      <span class="p">{</span>
        <span class="ss">url</span><span class="p">:</span> <span class="n">root_url</span><span class="p">,</span>
        <span class="ss">lastmod</span><span class="p">:</span> <span class="vi">@posts</span><span class="o">.</span><span class="n">first</span><span class="o">&amp;.</span><span class="n">updated_at</span> <span class="o">||</span> <span class="no">Time</span><span class="o">.</span><span class="n">current</span><span class="p">,</span>
        <span class="ss">changefreq</span><span class="p">:</span> <span class="s2">&#34;weekly&#34;</span><span class="p">,</span>
        <span class="ss">priority</span><span class="p">:</span> <span class="s2">&#34;1.0&#34;</span>
      <span class="p">},</span>
      <span class="p">{</span>
        <span class="ss">url</span><span class="p">:</span> <span class="n">blog_url</span><span class="p">,</span>
        <span class="ss">lastmod</span><span class="p">:</span> <span class="vi">@posts</span><span class="o">.</span><span class="n">first</span><span class="o">&amp;.</span><span class="n">updated_at</span> <span class="o">||</span> <span class="no">Time</span><span class="o">.</span><span class="n">current</span><span class="p">,</span>
        <span class="ss">changefreq</span><span class="p">:</span> <span class="s2">&#34;daily&#34;</span><span class="p">,</span>
        <span class="ss">priority</span><span class="p">:</span> <span class="s2">&#34;0.9&#34;</span>
      <span class="p">},</span>
      <span class="p">{</span>
        <span class="ss">url</span><span class="p">:</span> <span class="n">testimonials_url</span><span class="p">,</span>
        <span class="ss">lastmod</span><span class="p">:</span> <span class="mi">6</span><span class="o">.</span><span class="n">months</span><span class="o">.</span><span class="n">ago</span><span class="p">,</span>
        <span class="ss">changefreq</span><span class="p">:</span> <span class="s2">&#34;monthly&#34;</span><span class="p">,</span>
        <span class="ss">priority</span><span class="p">:</span> <span class="s2">&#34;0.7&#34;</span>
      <span class="p">}</span>
    <span class="o">]</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>With help from Cursor, or any other AI tools, you can pass the above template along with your <code>routes.rb</code> file for context, and it will update the controller to include all other endpoints in your site for complete <code>sitemap.xml</code> file.</p>
<p>Finally, add the XML view template to generate the final sitemap.</p>
<pre data-language="javascript"><code class="code-inline language-javascript"><span class="nx">xml</span><span class="p">.</span><span class="nx">instruct</span><span class="o">!</span> <span class="o">:</span><span class="nx">xml</span><span class="p">,</span> <span class="nx">version</span><span class="o">:</span> <span class="s2">&#34;1.0&#34;</span><span class="p">,</span> <span class="nx">encoding</span><span class="o">:</span> <span class="s2">&#34;UTF-8&#34;</span>
<span class="nx">xml</span><span class="p">.</span><span class="nx">urlset</span> <span class="nx">xmlns</span><span class="o">:</span> <span class="s2">&#34;http://www.sitemaps.org/schemas/sitemap/0.9&#34;</span> <span class="k">do</span>
  <span class="err">#</span> <span class="nx">Static</span> <span class="nx">pages</span> <span class="p">(</span><span class="nx">home</span><span class="p">,</span> <span class="nx">blog</span><span class="p">,</span> <span class="nx">testimonials</span><span class="p">,</span> <span class="nx">etc</span><span class="p">.)</span>
  <span class="err">@</span><span class="nx">static_pages</span><span class="p">.</span><span class="nx">each</span> <span class="k">do</span> <span class="o">|</span><span class="nx">page_data</span><span class="o">|</span>
    <span class="nx">xml</span><span class="p">.</span><span class="nx">url</span> <span class="k">do</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">loc</span> <span class="nx">page_data</span><span class="p">[</span><span class="o">:</span><span class="nx">url</span><span class="p">]</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">lastmod</span> <span class="nx">page_data</span><span class="p">[</span><span class="o">:</span><span class="nx">lastmod</span><span class="p">].</span><span class="nx">iso8601</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">changefreq</span> <span class="nx">page_data</span><span class="p">[</span><span class="o">:</span><span class="nx">changefreq</span><span class="p">]</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">priority</span> <span class="nx">page_data</span><span class="p">[</span><span class="o">:</span><span class="nx">priority</span><span class="p">]</span>
    <span class="nx">end</span>
  <span class="nx">end</span>

  <span class="err">#</span> <span class="nx">Dynamic</span> <span class="nx">pages</span> <span class="p">(</span><span class="nx">about</span><span class="p">,</span> <span class="nx">contact</span><span class="p">,</span> <span class="nx">etc</span><span class="p">.)</span>
  <span class="err">@</span><span class="nx">pages</span><span class="p">.</span><span class="nx">each</span> <span class="k">do</span> <span class="o">|</span><span class="nx">page</span><span class="o">|</span>
    <span class="nx">xml</span><span class="p">.</span><span class="nx">url</span> <span class="k">do</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">loc</span> <span class="nx">page_url</span><span class="p">(</span><span class="nx">page</span><span class="p">.</span><span class="nx">slug</span><span class="p">)</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">lastmod</span> <span class="nx">page</span><span class="p">.</span><span class="nx">updated_at</span><span class="p">.</span><span class="nx">iso8601</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">changefreq</span> <span class="s2">&#34;monthly&#34;</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">priority</span> <span class="s2">&#34;0.6&#34;</span>
    <span class="nx">end</span>
  <span class="nx">end</span>

  <span class="err">#</span> <span class="nx">Published</span> <span class="nx">blog</span> <span class="nx">posts</span>
  <span class="err">@</span><span class="nx">posts</span><span class="p">.</span><span class="nx">each</span> <span class="k">do</span> <span class="o">|</span><span class="nx">post</span><span class="o">|</span>
    <span class="nx">xml</span><span class="p">.</span><span class="nx">url</span> <span class="k">do</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">loc</span> <span class="nx">post_url</span><span class="p">(</span><span class="nx">post</span><span class="p">)</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">lastmod</span> <span class="nx">post</span><span class="p">.</span><span class="nx">updated_at</span><span class="p">.</span><span class="nx">iso8601</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">changefreq</span> <span class="s2">&#34;monthly&#34;</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">priority</span> <span class="s2">&#34;0.8&#34;</span>
    <span class="nx">end</span>
  <span class="nx">end</span>

  <span class="err">#</span> <span class="nx">Tag</span> <span class="nx">pages</span> <span class="p">(</span><span class="nx">only</span> <span class="nx">those</span> <span class="kd">with</span> <span class="nx">published</span> <span class="nx">posts</span><span class="p">)</span>
  <span class="err">@</span><span class="nx">tags</span><span class="p">.</span><span class="nx">each</span> <span class="k">do</span> <span class="o">|</span><span class="nx">tag</span><span class="o">|</span>
    <span class="nx">xml</span><span class="p">.</span><span class="nx">url</span> <span class="k">do</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">loc</span> <span class="nx">tag_url</span><span class="p">(</span><span class="nx">tag</span><span class="p">)</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">lastmod</span> <span class="nx">tag</span><span class="p">.</span><span class="nx">updated_at</span><span class="p">.</span><span class="nx">iso8601</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">changefreq</span> <span class="s2">&#34;monthly&#34;</span>
      <span class="nx">xml</span><span class="p">.</span><span class="nx">priority</span> <span class="s2">&#34;0.5&#34;</span>
    <span class="nx">end</span>
  <span class="nx">end</span>
<span class="nx">end</span></code></pre>
<p>That's it, now restart your Rails app and visit the <code>sitemap.xml</code> endpoint. You'll be presented with a sitemap.xml file, filled with all the pages of your website.</p>
<h2 id="i-have-a-sitemap-now-what"><strong>I have a sitemap, now what?</strong></h2>
<p>Now you can either wait for Google to read that sitemap next time it decides to visit your website, or you can be proactive and submit it to Google. For this, you will need a <a href="https://search.google.com/search-console/about">Google Search Console</a> account. <strong>Not Google Analytics, but Google Search Console.</strong> These are two completely separate things.</p>
<p>First, get set up on <a href="https://search.google.com/search-console/about">Search Console</a>. You'll have to verify that you're the owner of the site using your domain registrar (takes less than a minute) and then go to the dashboard. Click on &quot;Sitemaps&quot;.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/b3s7mzfrwexm18atutchuiov2baw.png" alt="google-search-console-sitemaps.png" loading="lazy">
  <figcaption class="attachment__caption">Google Search Console - Sitemaps</figcaption>
</figure><p>You'll be prompted to enter the sitemap URL here. Just make sure you can access the URL in a separate browser tab, and then enter it in the input field. Click submit.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/rf6wm2nyuwyjmiipuoq3i199xx40.png" alt="google-search-console-enter-sitemap.png" loading="lazy">
  <figcaption class="attachment__caption">Enter Sitemap in Google Search Console</figcaption>
</figure><p>That's it. You've now told Google what links it should crawl and have also provided additional metadata which helps with crawling and indexing. Now keep writing helpful and useful posts and let the wheels of SEO grind.</p>
<p>But wait, there one other bonus tip I wanted to share. <strong>Every time you publish a new post, tell Google.</strong></p>
<h2 id="submit-new-posts-on-search-console">Submit New Posts on Search Console</h2>
<p>Let's say you've written a new article or added a new page on your website. You can either wait for Google to crawl it, or you can actively tell Google. For this, go to Search Console, and at the top you'll see this input field: <strong>&quot;Inspect any URL&quot;.</strong></p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/1aebljjk9ehh09qmyzj68f002y9v.png" alt="google-search-console-inspect-url.png" loading="lazy">
  <figcaption class="attachment__caption">Inspect a URL in Google Search Console</figcaption>
</figure><p>Enter the URL of your new post, and it will show a screen similar to this.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/yqrrvq111lm1fptlg1zbxl5144me.png" alt="request-indexing.png" loading="lazy">
  <figcaption class="attachment__caption">Request Indexing in Google Search Console</figcaption>
</figure><p>Click on <strong>Request Indexing</strong>, and you're good to go. Google will add the link to its list of pages to be crawled.</p>
<p>Now go write some awesome posts and share them with the world.</p>

</div>
]]></content:encoded><pubDate>Fri, 11 Jul 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/sitemaps-rails</link><guid isPermaLink="true">https://writesoftwarewell.com/sitemaps-rails</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Polymorphic URLs with direct Router Helper</title><description>The Rails router's direct method lets you create custom url and path helpers, which is especially useful for polymorphic models and delegated types. This post shows how to use a single custom helper to generate URLs for different models, with a practical example from the open source Maybe project.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>While reading the source code for the <a href="https://github.com/maybe-finance/maybe">Maybe</a> project (which is a really good Rails codebase that follows most of the Rails best practices and conventions), I came across this code in the router config file. It uses the Rails routing feature called <code>direct</code> to create custom URL helpers for a polymorphic model.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">direct</span> <span class="ss">:entry</span> <span class="k">do</span> <span class="o">|</span><span class="n">entry</span><span class="p">,</span> <span class="n">options</span><span class="o">|</span>
  <span class="k">if</span> <span class="n">entry</span><span class="o">.</span><span class="n">new_record?</span>
    <span class="n">route_for</span> <span class="n">entry</span><span class="o">.</span><span class="n">entryable_name</span><span class="o">.</span><span class="n">pluralize</span><span class="p">,</span> <span class="n">options</span>
  <span class="k">else</span>
    <span class="n">route_for</span> <span class="n">entry</span><span class="o">.</span><span class="n">entryable_name</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="n">options</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>At first glance, I didn't understand what it was doing, as I've personally never had to use the <code>direct</code> method like this in my Rails projects so far, so decided to do some reading and wanted to share everything I learned.</p>
<p><strong>First, what is the</strong> <strong><code>direct</code></strong> <strong>method in the Rails router?</strong></p>
<p>The <code>direct</code> helper lets you defined custom named route helpers that generate URLs based on custom logic, rather than the default resourceful routes. You can then use these helpers throughout your application, just like any other URL helpers in Rails.</p>
<blockquote>
<p>It's particularly useful when the URL for a model doesn't follow the standard conventions that resourceful routing handles automatically.</p>
</blockquote>
<p>In the simplest case, you can simply return a URL that you'd like to use when that custom URL helper is used. Consider the following example.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">direct</span> <span class="ss">:course_landing_page</span> <span class="k">do</span>
  <span class="s2">&#34;https://writesoftwarewell.com/courses&#34;</span>
<span class="k">end</span></code></pre>
<p>This will generate following URL helper methods</p>
<ul>
<li><code>course_landing_page_url</code> returns https://writesoftwarewell.com/courses</li>
<li><code>course_landing_page_path</code> returns <code>/courses</code>.</li>
</ul>
<p>If you pass any arguments to the helper, they get forwarded to the direct block.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">direct</span> <span class="ss">:greeting_page</span> <span class="k">do</span> <span class="o">|</span><span class="n">user</span><span class="o">|</span>
  <span class="s2">&#34;https://writesoftwarewell.com/greet/</span><span class="si">#{</span><span class="n">user</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s2">&#34;</span>
<span class="k">end</span></code></pre>
<p>This generates the helpers <code>greeting_page_url</code> and <code>greeting_page_path</code>. Assuming <code>matz.name</code> returns <code>&quot;yukihiro&quot;</code>, you can use them as follows:</p>
<ul>
<li><code>greeting_page_url(matz)</code> returns https://writesoftwarewell.com/greet/yukihiro</li>
<li><code>greeting_page_path(matz)</code> returns <code>greet/yukihiro</code> .</li>
</ul>
<p>To learn more about the basic usage of the direct method, check out the following post: <a href="https://writesoftwarewell.com/direct-custom-url-helpers-rails">Custom URL Helpers in Rails with the direct Method</a></p>
<p>The <code>direct</code> method is pretty flexible and you can encapsulate complex or polymorphic path logic in the block, which is what the Maybe router is doing.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">direct</span> <span class="ss">:entry</span> <span class="k">do</span> <span class="o">|</span><span class="n">entry</span><span class="p">,</span> <span class="n">options</span><span class="o">|</span>
  <span class="k">if</span> <span class="n">entry</span><span class="o">.</span><span class="n">new_record?</span>
    <span class="n">route_for</span> <span class="n">entry</span><span class="o">.</span><span class="n">entryable_name</span><span class="o">.</span><span class="n">pluralize</span><span class="p">,</span> <span class="n">options</span>
  <span class="k">else</span>
    <span class="n">route_for</span> <span class="n">entry</span><span class="o">.</span><span class="n">entryable_name</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="n">options</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This code defines a custom route helper called <code>entry_path</code> and <code>entry_url</code>. When you call <code>entry_path(entry)</code>, where <code>entry</code> can be a <a href="https://guides.rubyonrails.org/association_basics.html#polymorphic-associations">polymorphic object</a> or a <a href="https://api.rubyonrails.org/classes/ActiveRecord/DelegatedType.html">delegated type</a>, Rails will use this block to figure out what URL path to return for the given <code>entry</code> object.</p>
<p>Let's assume that <code>Entry</code> is a polymorphic model and can be a <code>Transaction</code>, <code>Account</code>, or <code>Trade</code>, etc.</p>
<p><strong>What does the block do?</strong></p>
<ul>
<li>If the entry is a new record, i.e. <code>entry.new_record?</code> returns <code>true</code>, Rails will return the value generated by the following code:</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">route_for</span> <span class="n">entry</span><span class="o">.</span><span class="n">entryable_name</span><span class="o">.</span><span class="n">pluralize</span><span class="p">,</span> <span class="n">options</span></code></pre>
<p>This means, generate the path for the pluralized entryable name, e.g. if <code>entry.entryable_name</code> is &quot;transaction&quot;, Rails will return the value of generated by calling <code>route_for &quot;transactions&quot;, options</code> which ultimately generates the path for the transactions resource, i.e. <code>transactions_path</code>, which is <code>/transactions</code>.</p>
<p>I'm guessing it's used for the &quot;new&quot; forms, where you want to POST to the collection.</p>
<p>Example:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">entry</span> <span class="o">=</span> <span class="no">Entry</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="ss">entryable</span><span class="p">:</span> <span class="no">Transaction</span><span class="o">.</span><span class="n">new</span><span class="p">)</span>
<span class="n">entry_path</span><span class="p">(</span><span class="n">entry</span><span class="p">)</span>

<span class="c1"># =&gt; transactions_path, i.e. &#34;/transactions&#34;</span></code></pre>
<p>Since the entry was not saved, it routed to the collection path for the entryable type.</p>
<ul>
<li>If the entry is persisted (the else condition), it will return the value generated by this code:</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">route_for</span> <span class="n">entry</span><span class="o">.</span><span class="n">entryable_name</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="n">options</span></code></pre>
<p>This means, generate the path for the singular entryable name and pass the entry as the argument to the helper, i.e. <code>transaction_path(entry)</code></p>
<p>Example:</p>
<pre data-language="javascript"><code class="code-inline language-javascript"><span class="nx">entry</span> <span class="o">=</span> <span class="nx">Entry</span><span class="p">.</span><span class="nx">find</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="err">#</span> <span class="nx">assume</span> <span class="k">this</span> <span class="nx">entry</span> <span class="nx">is</span> <span class="nx">a</span> <span class="nx">transaction</span>
<span class="nx">entry_path</span><span class="p">(</span><span class="nx">entry</span><span class="p">)</span>

<span class="err">#</span> <span class="p">=&gt;</span> <span class="nx">transaction_path</span><span class="p">(</span><span class="nx">entry</span><span class="p">),</span> <span class="nx">i</span><span class="p">.</span><span class="nx">e</span><span class="p">.</span> <span class="s2">&#34;/transactions/1&#34;</span></code></pre>
<p>Since the entry was saved, it routed to the member path for the entryable type.</p>
<h2 id="why-use-this"><strong>Why use this?</strong></h2>
<p>If you have a polymorphic model that can represent multiple types, a single helper can generate the correct path for any type.</p>
<p>In Maybe, an <code>Entry</code> is a polymorphic model that can be one of several types, such as a <code>Transaction</code>, <code>Trade</code>, or <code>Valuation</code>. The URL for an entry should depend on what kind of entry it is.</p>
<p>In addition, the logic forks based on whether the entry has been saved to the database. This is a common pattern in most web applications, where you have to use a different URL in forms, where a new object should POST to a collection URL <code>/transactions</code>, while a form for an existing object should PATCH to a member URL, like <code>/transactions/123</code>.</p>
<h3 id="how-to-use-it">How to use it?</h3>
<pre data-language="javascript"><code class="code-inline language-javascript"><span class="o">&lt;%=</span> <span class="nx">link_to</span> <span class="s2">&#34;View entry&#34;</span><span class="p">,</span> <span class="nx">entry_path</span><span class="p">(</span><span class="nx">entry</span><span class="p">)</span> <span class="o">%&gt;</span></code></pre>
<p>This will generate the correct path for the given entry, whether it's a new entry or a persisted entry, regardless of its underlying type.</p>
<p>The following table summarizes it.</p>
<figure class="attachment attachment--preview">
  <img src="https://writesoftwarewell.com/media/o8ehpwh4f1dfywva9kye71tj1i3r.png" alt="direct-route-helper.png" loading="lazy">
  <figcaption class="attachment__caption">Direct Route Helper</figcaption>
</figure><p>Basically, you can use the direct helper method to handle URL generation for polymorphic types. Creating a single URL helper method that hides the complexity of figuring out the type of the entry and whether the entry is new or an existing record.</p>

</div>
]]></content:encoded><pubDate>Tue, 08 Jul 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/polymorphic-urls-with-rails-direct-route</link><guid isPermaLink="true">https://writesoftwarewell.com/polymorphic-urls-with-rails-direct-route</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Working Effectively with AI as a Developer</title><description>I started as a sceptic, but now I'm a convert and a heavy user of AI for everyday programming, and wanted to write down some common patterns and prompts for working with AI tools that I’ve found useful in my own development workflow as well as those I learned from other experienced developers.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>Over the past year, I’ve started heavily using AI tools like Cursor and ChatGPT in my everyday development workflow. They’re not a replacement for thinking, but I found them as excellent assistants for learning, debugging, refactoring, and accelerating implementation work.</p>
<p>I wanted to write down some common patterns I’ve observed in my own workflow, plus the patterns I’ve come across from other experienced developers and the ones I found online.</p>
<p><em>Btw, this is by no means an exhaustive list; if you know more patterns and best practices, I'd love to hear them. Also, I'm</em> <em><strong>not</strong></em> <em>sharing them as an AI expert / influencer, just a fellow practitioner and user of these tools.</em></p>
<hr>
<h3 id="tldr">TL;DR:</h3>
<ul>
<li>the usefulness of these tools depends directly on the quality of your prompts</li>
<li>understand before you vibe</li>
<li>verify your understanding</li>
<li>make the model understand the related code</li>
<li>plan and design incrementally</li>
<li>refactor with explicit goals (perf / idiomatic / readability)</li>
<li>Use them as rubber-ducks</li>
</ul>
<p>The very first thing to know is that <strong>the usefulness of these tools depends directly on the quality of your prompts.</strong> Garbage in, garbage out. Vague input leads to vague output and hallucinations. Precise, context-rich prompts are far more likely to produce relevant, specific, and useful responses.</p>
<p><strong>Understand before you vibe.</strong> Before asking ChatGPT or Cursor to implement a feature, I'll often use them to understand how related code works. I’ll give it a controller or model class and ask for a deep dive. &quot;I want to understand how this <strong>{feature/function/class/module}</strong> works. Please analyze the relevant code and give me a detailed explanation.&quot;</p>
<p><strong>Verify your understanding.</strong> Once I’ve got a good understanding of the related code, I proceed with building the feature. &quot;Here’s my <strong>{understanding}</strong>. Is this correct? If not, what am I missing?&quot;</p>
<p><strong>Make the model understand the code it will be working on.</strong> I like to treat these tools as fellow developers. Before asking them to build a feature, ask them to do a deep-dive in the codebase to understand how the existing, related code works. Then ask them to summarize their understanding. Make sure you understand it and only then provide the feature specification and ask them for implementation. </p>
<p><strong>Don’t ask vague questions like “Why isn’t my code working?”.</strong> Instead, structure the problem clearly. &quot;Here is the <strong>{problem}</strong>. Here is the <strong>{code}</strong>. It should do <strong>{this}</strong>. Currently it’s doing <strong>{this}</strong>. Why?&quot;</p>
<p>This helps the model reason through the bug more effectively. If a function should return a particular output for a specific input, say so explicitly. The clarity and understanding benefits both you and the model. &quot;This function should return <strong>{this}</strong>, when the input is <strong>{this}</strong>. Implement / fix the function.&quot;</p>
<p><strong>Plan and design incrementally, don't one-shot it.</strong> When working on a new feature, I usually start with this: &quot;I’m building <strong>{feature}</strong>. Here are the <strong>{requirements}</strong>. First, give me high-level implementation strategy. Then we’ll implement it step-by-step.&quot;</p>
<p>Once I have that, I work through the implementation step-by-step, either myself or with Cursor generating suggestions inline. For large or complex features, the best practice is to break them into smaller subproblems first. Once the plan is clear, you can feed each part into Cursor and implement iteratively.</p>
<p><strong>Refactoring and code reviews.</strong> &quot;Here’s the <strong>{function/class}</strong>. Refactor it for readability / performance / idiomatic Ruby/Go.&quot; The responses are not always perfect, but they often give new ideas or help me evaluate tradeoffs. Sometimes I’ll use ChatGPT to compare two versions of a function or summarize the differences.</p>
<p>When I encounter unfamiliar code or behavior, I write down my understanding and ask: &quot;This is my <strong>{understanding},</strong> Is this correct? If not, what am I missing?&quot; This is useful for identifying gaps in my mental model, especially when dealing with metaprogramming, concurrency, or deep Rails internals.</p>
<p>To squeeze the most benefit and effectiveness out of these wonderful tools:</p>
<ul>
<li>Ask specific, structured questions</li>
<li>Confirm understanding before implementing</li>
<li>Break large problems into manageable chunks</li>
<li>Treat them as code reviewers and <a href="https://blog.codinghorror.com/rubber-duck-problem-solving/">rubber ducks</a></li>
</ul>
<p>Remember the classic advice from Jeff Atwood (Coding Horror), creator of Stack Overflow, which equally applies to working with AI tools:</p>
<blockquote>
<p>At Stack Exchange, <strong>we insist that people who ask questions</strong> <em><strong>put some effort into their question</strong></em><strong>, and we’re kind of strict about it</strong>. That is, when you set out to ask a question, you should…</p>
<p>- Describe what’s happening in sufficient detail that we can follow along. Provide the necessary background for us to understand what’s going on, even if we aren’t experts in your particular area.</p>
<p>- Tell us why you <em>need</em> to know the answer. What led you here? Is it idle curiosity or is this somehow blocking you on a project? We don’t need your whole life story, just give us some context here.</p>
<p>- Share your research on your problem; what have you found so far? Why didn’t it work? And if you didn’t do any research… should you even be asking? If you’re inviting us to spend our valuable time helping you, it’s only fair that you put in a reasonable amount of your valuable time into crafting a decent question. Help us help you!</p>
</blockquote>
<p>Same goes for AI. Help it to help you!</p>

</div>
]]></content:encoded><pubDate>Thu, 19 Jun 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/working-effectively-with-ai-tools-as-developer</link><guid isPermaLink="true">https://writesoftwarewell.com/working-effectively-with-ai-tools-as-developer</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>How to Inspect the Sequence of Controller Callbacks in Rails</title><description>This post shows how to inspect the sequence of before, after, and around callbacks in Rails controllers by adding a small initializer. Useful for understanding callback order in applications with complex controller hierarchies or shared concerns. I learned this trick while reading the Rails tests.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>While debugging a Rails app, sometimes it's useful to see the full list of callbacks that are set to run before, after, or around a controller action, in the exact sequence they will run. This is especially true in applications with a deep controller inheritance hierarchy or a heavy use of <a href="https://writesoftwarewell.com/how-rails-concerns-work-and-how-to-use-them">concerns</a> with conditional callbacks.</p>
<p>Here's a small trick you can use to inspect the full list of callbacks for a controller. I just learned this today while trying to make sense of a confusing callback sequence in a fairly complex controller. <strong>As always, please let me know if there's a better or more idiomatic way to do this.</strong> </p>
<p>First, add a new initializer with the following code under the <code>initializers</code> directory.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># config/initializers/callbacks.rb</span>

<span class="k">class</span> <span class="nc">ActionController</span><span class="o">::</span><span class="no">Base</span>
  <span class="k">class</span> <span class="o">&lt;&lt;</span> <span class="nb">self</span>
    <span class="no">CALLBACK_KINDS</span> <span class="o">=</span> <span class="o">[</span><span class="ss">:before</span><span class="p">,</span> <span class="ss">:after</span><span class="p">,</span> <span class="ss">:around</span><span class="o">].</span><span class="n">freeze</span>

    <span class="no">CALLBACK_KINDS</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">kind</span><span class="o">|</span>
      <span class="n">define_method</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">#{</span><span class="n">kind</span><span class="si">}</span><span class="s2">_actions&#34;</span><span class="p">)</span> <span class="k">do</span>
        <span class="n">_process_action_callbacks</span><span class="o">.</span><span class="n">select</span> <span class="p">{</span> <span class="o">|</span><span class="n">c</span><span class="o">|</span> <span class="n">c</span><span class="o">.</span><span class="n">kind</span> <span class="o">==</span> <span class="n">kind</span> <span class="p">}</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:filter</span><span class="p">)</span>
      <span class="k">end</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p><em>If you're not familiar with initializers, check out this post</em>:</p>
<p><a href="https://writesoftwarewell.com/introduction-to-rails-initializers">A Brief Introduction to Rails Initializers: Why, What, and How</a></p>
<p>The above initializer code loops through the supported kinds of callbacks and uses <code>define_method</code> to create a method for each one. Inside each method, it filters <code>_process_action_callbacks</code> by the specific kind and then maps to get the actual method names (or blocks) that will be invoked.</p>
<p>This dynamically defines three methods on every controller class:</p>
<ul>
<li><code>before_actions</code></li>
<li><code>after_actions</code></li>
<li><code>around_actions</code></li>
</ul>
<p>Each method returns an array of the corresponding callback methods for that controller, in the order they'll be invoked.</p>
<p>For example, here's the <code>before_action</code> method the above code will generate:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">ActionController</span><span class="o">::</span><span class="no">Base</span>
  <span class="k">class</span> <span class="o">&lt;&lt;</span> <span class="nb">self</span>
    <span class="k">def</span> <span class="nf">before_actions</span>
      <span class="n">filters</span> <span class="o">=</span> <span class="n">_process_action_callbacks</span><span class="o">.</span><span class="n">select</span> <span class="p">{</span> <span class="o">|</span><span class="n">c</span><span class="o">|</span> <span class="n">c</span><span class="o">.</span><span class="n">kind</span> <span class="o">==</span> <span class="ss">:before</span> <span class="p">}</span>
      <span class="n">filters</span><span class="o">.</span><span class="n">map!</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:filter</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<h2 id="usage">Usage</h2>
<p>This is how you use the generated methods.</p>
<pre data-language="javascript"><code class="code-inline language-javascript"><span class="nx">PostsController</span><span class="p">.</span><span class="nx">before_actions</span>
<span class="p">=&gt;</span> 
<span class="p">[</span><span class="o">:</span><span class="nx">verify_authenticity_token</span><span class="p">,</span>
 <span class="o">:</span><span class="nx">set_site_info</span><span class="p">,</span>
 <span class="o">:</span><span class="nx">configure_permitted_parameters</span><span class="p">,</span>
 <span class="o">:</span><span class="nx">authenticate_user</span><span class="o">!</span><span class="p">,</span>
 <span class="o">:</span><span class="nx">set_post</span><span class="p">,</span>
 <span class="o">:</span><span class="nx">set_tags</span><span class="p">]</span>

<span class="nx">PostsController</span><span class="p">.</span><span class="nx">after_actions</span>
<span class="p">=&gt;</span> <span class="p">[</span><span class="o">:</span><span class="nx">verify_same_origin_request</span><span class="p">]</span>

<span class="nx">PostsController</span><span class="p">.</span><span class="nx">around_actions</span>
<span class="p">=&gt;</span> <span class="p">[</span><span class="o">:</span><span class="nx">turbo_tracking_request_id</span><span class="p">]</span></code></pre>
<p>This tells you the exact sequence in which your callbacks are run. Very useful when debugging.</p>
<h2 id="how-it-works">How it Works</h2>
<p>Internally, Rails stores the list of action callbacks for each controller in a private method called <code>_process_action_callbacks</code>. Each item in that list is a <code>Callback</code> object with metadata like:</p>
<ul>
<li><code>kind</code>: <code>:before</code>, <code>:after</code>, or <code>:around</code></li>
<li><code>filter</code>: the method or block to be called</li>
<li><code>if</code> / <code>unless</code> conditions (as Procs)</li>
</ul>
<p>Even though it’s not part of the public API, it’s a clean and reliable way to introspect your controller’s filters for debugging or documentation purposes.</p>
<p>Now, often you'll hear that callbacks is a bad practice / anti-pattern. I personally find them very useful to manage side-logic not directly related to the action, just like concerns. Here's a fantastic video from DHH that shows callbacks in the wild, along with some practical and useful commentary on their usage.</p>
<p><a href="https://www.youtube.com/watch?v=m1jOWu7woKM">On Writing Software Well #2: Using callbacks to manage auxiliary complexity</a></p>
<p><strong>Reading the Rails Source Is Worth It.</strong></p>
<p>Reading the Rails codebase, especially the tests, often leads to discovery of simple and useful patterns like this one.</p>
<p>I came across this trick while reading the Rails source code, looking for a built-in way to inspect the callback sequence. There wasn’t a ready-made method, but in <a href="https://github.com/rails/rails/blob/82e9029bbf63a33b69f007927979c5564a6afe9e/actionpack/test/controller/filters_test.rb#L13"><code>filters_test.rb</code></a>, I found some test code that did exactly what I needed. From there, it was just a matter of pulling it into an initializer and generalizing it.</p>
<p>If you're ever stuck, or wondering &quot;is there a way to…&quot;, a quick dive into the source is often more productive than getting a ready-made answer online.</p>

</div>
]]></content:encoded><pubDate>Tue, 17 Jun 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/rails-controller-callback-sequence</link><guid isPermaLink="true">https://writesoftwarewell.com/rails-controller-callback-sequence</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Thoughts on Freelancing for Web Developers</title><description>After three years of freelancing and over a year of running my own software studio, here're some scattered thoughts on freelancing as a software developer, especially around web development.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p>If you’re an experienced web developer looking to go freelance, or just line up a few solid side gigs, there’s a simple shift that can make your life much easier: <strong>stop targeting upwork / individuals / mom-and-pop shops, and sell to businesses.</strong> Focus on clients who already know how to work with developers and have long-term needs.</p>
<p>The typical local mom and pop coffee shop / gym / yoga studio might sound like a great client: they’re nearby, they need a website, and they’re impressed when you mention your design and development skills. In reality, these clients often lack the budget, project management experience, or long-term need for software that makes them worthwhile.</p>
<p>Your best bet for reliable, steady work is either with design, marketing, and interactive agencies on one end, and small-to-mid sized software companies on the other end.</p>
<p><strong>Agencies (or businesses) are just better clients.</strong></p>
<p>Agencies are <em>designed</em> to work with freelancers. They often need extra development help on short notice. They’ve done this before. They have project managers, creative briefs, timelines, and client expectations. Most importantly, they typically have <em>ongoing</em> work, and <strong>when you deliver well on one project, they come back with more.</strong></p>
<p>Even if they don’t have something for you right now, most agencies keep a vetted list of freelancers they can call on when things pick up. Getting on that list is often the difference between feast and famine in freelancing. <strong>Case in point:</strong> Since incorporating last year, I've frequently worked with a few solid designers on an ongoing basis, and have a few developers who I reach out to whenever I don't have capacity to take on more work.</p>
<p>You might not even need to specialize in front-end design work. Agencies need backend help too: building custom CMS or integrating with external software, building internal dashboards, handling weird deployment setups, getting multiple applications talk to each other via APIs, and so on. Your Rails skills are so, so valuable in that context, and more so if you’re comfortable working alongside a front-end designer or handling both sides of the project.</p>
<p>💡 Often, getting entry as a web developer gets you in the door for more interesting back-end projects that pay much, much more.</p>
<p><strong>Target bigger businesses</strong>. In addition to agencies, consider reaching out to mid-sized companies, especially those that have a dedicated marketing, communications, or software team. These businesses often have budget for freelancers, but aren’t so big that they require going through five rounds of interview rounds.</p>
<p>Look for companies where your Rails skills can help automate, integrate, or modernize something, and where the person you contact will understand what you’re offering.</p>
<p>Target companies who <em>already know</em> <em><strong>how to work with developers</strong></em> and have repeat needs. It takes just as much time to land a $500 marketing website from a local coffee shop as it does to land a $20,000 integration project from an agency. But only one of those turns into repeat work, referrals, and long-term relationships.</p>
<p><strong>The goal is to have repeatable, steady work.</strong> If you want freelancing to work, you need a client base that’s reliable, professional, and worth your time. Agencies and mid-sized software businesses are perfect clients for software / web freelancers.</p>
<p>It’s not glamorous, and it may not get you a large following on Twitter. But if you want to get paid to write Rails, learn by doing, and build a reputation, this is a really good way.</p>
<p>And it beats waiting around for someone to choose you from hundreds of thousands of other profiles from Upwork / Elance.</p>
<blockquote>
<p>Btw, I finally set up a Twitter account. Been avoiding it for years, but <a href="https://x.com/typeangled">here I am</a>. If you're on Twitter, let's connect.</p>
</blockquote>

</div>
]]></content:encoded><pubDate>Sun, 15 Jun 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/thoughts-on-freelancing-web-developers</link><guid isPermaLink="true">https://writesoftwarewell.com/thoughts-on-freelancing-web-developers</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Redirects in Rails: Manual, Helper, and Internals</title><description>In this post, we’ll explore how redirects work in Rails: what they are, how to redirect manually, and how the redirect_to method simplifies things. We’ll cover common use cases, security considerations, and even dig into the Rails source to see how redirect_to works under the hood.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <blockquote>
<p>This is the seventh post in the series on <a href="https://writesoftwarewell.com/tag/controllers">Rails controllers</a>.</p>
</blockquote>
<p>Redirects are an important part of the web, and Rails gives us a clean and expressive way to use them with the <code>redirect_to</code> helper method.</p>
<p>But what's actually going on when you call <code>redirect_to</code>?</p>
<p>It's easy to treat it as a magical Rails incantation that just sends users elsewhere, but it's important to understand how it really works. Knowing what happens at the HTTP level, and how Rails constructs that response, helps you reason about edge cases, debug redirect loops, or customize behavior in advanced scenarios.</p>
<p>Let’s walk through how redirects work, how to implement one manually in Rails, how the <code>redirect_to</code> helper simplifies things, and what’s actually happening under the hood.</p>
<p><strong>Note:</strong> This post focuses on redirects from Rails controllers. For router-level redirects, check out the following post from my Rails Router Handbook: <a href="https://writesoftwarewell.com/how-to-redirect-rails-router">How to Redirect Requests from Rails Router</a></p>
<hr>
<h2></h2>
<p>What is a Redirect?</p>
<p>A redirect is an instruction sent by a server to a browser (or any HTTP client), telling it to make a new request to a different URL.</p>
<p>At its core, an HTTP redirect is a response from the server that includes a specific status code and a <code>Location</code> header, instructing the browser to initiate a new request to a different URL.</p>
<p>For example, here’s what a basic HTTP redirect response might look like:</p>
<pre data-language="text"><code class="code-inline language-text">HTTP/1.1 302 Found
Location: /login
Content-Length: 0
Content-Type: text/html; charset=utf-8</code></pre>
<p>When a browser receives a response with a <code>3xx</code> HTTP status and a <code>Location</code> header, it knows it needs to stop processing the current response and initiate a new request to the URL specified in that header.</p>
<p>There are two broad types of redirects: <strong>temporary</strong> and <strong>permanent</strong>.</p>
<ul>
<li><strong>Permanent redirects</strong> (like <code>301 Moved Permanently</code> or <code>308 Permanent Redirect</code>) signal that the resource has been permanently moved to a new location. Search engines will update their indexes and transfer SEO ranking to the new URL.</li>
<li><strong>Temporary redirects</strong> (like <code>302 Found</code>, <code>303 See Other</code>, or <code>307 Temporary Redirect</code>) indicate that the resource has been moved, but only temporarily. Clients should continue to use the original URL for future requests.</li>
</ul>
<p>Choosing the correct type of redirect is especially important for SEO:</p>
<ul>
<li>Use a <code>301</code> or <code>308</code> if you want search engines to index the new URL and deprecate the old one.</li>
<li>Use a <code>302</code>, <code>303</code>, or <code>307</code> if the change is temporary or during A/B testing.</li>
</ul>
<p>Search engines interpret these status codes differently, and misuse can lead to ranking loss or indexing errors. When in doubt, consider what you want to happen over the long term.</p>
<h3 id="how-status-codes-affect-the-follow-up-request">How Status Codes Affect the Follow-up Request</h3>
<p>Redirect status codes don’t just tell the browser where to go, but they also affect how the follow-up request is made. Specifically, some redirect codes instruct the browser to discard the original request method and body, and use a simple GET instead. Others preserve the original method and payload.</p>
<p>Here’s how different status codes handle method preservation:</p>
<ul>
<li><strong>301 Moved Permanently, 302 Found</strong>: The behavior varies by client. Many browsers treat it as a GET redirect, even if the original request was a POST. This is for historical reasons and can lead to inconsistent behavior.</li>
<li><strong>303 See Other</strong>: Clearly instructs the client to make a GET request to the new location, regardless of the original method. <strong>This is the safest and most predictable way to redirect after form submissions.</strong></li>
<li><strong>307 Temporary Redirect, 308 Permanent Redirect</strong>: Preserves the original HTTP method and body. If the original request was a POST, the redirected request will also be a POST.</li>
</ul>
<p>This distinction is subtle but important. If you’re redirecting after a destructive or sensitive action, and want to ensure the client switches to a safe, idempotent method like GET, choose <code>303 See Other</code>. <strong>It will always result in a GET.</strong> </p>
<p>If you want to preserve the original method and payload, use <code>307</code> or <code>308</code> (for example, when redirecting between API endpoints that expect POST bodies).</p>
<hr>
<h2 id="redirecting-manually-in-rails">Redirecting Manually in Rails</h2>
<p>Before we look at how to use the <code>redirect_to</code> method in Rails, let’s take a moment to understand what it’s actually doing under the hood. Rails provides the helper to abstract away the complexity, but it’s worth knowing how you could implement a redirect manually.</p>
<p>The goal here is to send an HTTP response that tells the browser: <strong>&quot;Stop what you're doing and go load this other URL instead.&quot;</strong> To do that, we need to manually set the correct status code (usually 302 for a temporary redirect), set the <code>Location</code> header, and ensure the response body is appropriately empty.</p>
<p>Let’s see how you’d implement a basic redirect in Rails without using <code>redirect_to</code>. In this example, our goal is to log the user out and then redirect them to the root path of the application, i.e. the homepage.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">SessionsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
  <span class="k">def</span> <span class="nf">destroy</span>
    <span class="n">reset_session</span>

    <span class="n">response</span><span class="o">.</span><span class="n">status</span> <span class="o">=</span> <span class="mi">302</span>
    <span class="n">response</span><span class="o">.</span><span class="n">headers</span><span class="o">[</span><span class="s1">&#39;Location&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="n">root_path</span>
    <span class="nb">self</span><span class="o">.</span><span class="n">response_body</span> <span class="o">=</span> <span class="kp">nil</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This does the following:</p>
<ul>
<li>It sets the HTTP status to <code>302 Found</code> (the default for temporary redirects).</li>
<li>It sets the <code>Location</code> header to the destination URL.</li>
<li>It clears the response body.</li>
</ul>
<p>But as you can see, it’s verbose and easy to get wrong. Forgetting to set the status code or leaving a response body in can cause unexpected behavior.</p>
<p>That’s where <code>redirect_to</code> comes in.</p>
<hr>
<h2 id="the-redirect_to-helper">The redirect_to Helper</h2>
<p><a href="https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to">Rails prov</a>ides a convenient method: <a href="https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to"><code>redirect_to</code></a>, which wraps up all the low-level redirect logic into one clean call.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">SessionsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
  <span class="k">def</span> <span class="nf">destroy</span>
    <span class="n">reset_session</span>
    <span class="n">redirect_to</span> <span class="n">root_path</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Much simpler. </p>
<p>The <code>redirect_to</code> method automatically:</p>
<ul>
<li>Sets the correct status code (<code>302 Found</code> by default).</li>
<li>Sets the <code>Location</code> header.</li>
<li>Ensures the response body is empty.</li>
</ul>
<p>It also gives you flexibility. You can customize the status code:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="n">root_path</span><span class="p">,</span> <span class="ss">status</span><span class="p">:</span> <span class="ss">:see_other</span></code></pre>
<p>Or redirect to full URLs, named routes, polymorphic paths, or even use fallback locations with <code>redirect_back</code>.</p>
<hr>
<h2 id="exploring-options-for-redirect_to">Exploring Options for redirect_to</h2>
<p>The <code>redirect_to</code> helper supports a variety of inputs, making it flexible and expressive. According to the <a href="https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to">Rails documentation</a>, here are the supported formats:</p>
<p><strong>String URL:</strong> Redirects to a full URL. If the host + protocol is not provided, the current protocol and host is prepended to the string.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="s2">&#34;https://example.com&#34;</span>
<span class="n">redirect_to</span> <span class="s2">&#34;/projects&#34;</span></code></pre>
<p><strong>Named route or path helper:</strong> Redirects using a named route.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="n">dashboard_path</span></code></pre>
<p><strong>Record:</strong> The URL will be generated by calling <a href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for"><code>url_for</code></a> with the <code>options</code>, which will reference a named URL for that record.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="vi">@product</span></code></pre>
<p><strong>Hash of route params:</strong> The URL will be generated by calling <a href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for"><code>url_for</code></a> with the <code>options</code>.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="ss">controller</span><span class="p">:</span> <span class="s1">&#39;products&#39;</span><span class="p">,</span> <span class="ss">action</span><span class="p">:</span> <span class="s1">&#39;show&#39;</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="mi">1</span></code></pre>
<p><strong>Custom status code:</strong> You can pass status as a symbol (<code>:see_other</code>) or an integer (<code>301</code>).</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="n">root_path</span><span class="p">,</span> <span class="ss">status</span><span class="p">:</span> <span class="ss">:moved_permanently</span></code></pre>
<p><strong>Proc:</strong> A block that will be executed in the controller’s context.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="nb">proc</span> <span class="p">{</span> <span class="n">edit_post_url</span><span class="p">(</span><span class="vi">@post</span><span class="p">)</span> <span class="p">}</span></code></pre>
<p>All these options make <code>redirect_to</code> a very flexible tool in your Rails toolbox.</p>
<h2 id="redirecting-to-external-urls-safely">Redirecting to External URLs Safely</h2>
<p>By default, <a href="https://"><code>Rails</code></a> protects against redirecting to external hosts for your app’s safety, so called open redirects. For example, the following redirect will raise an <code>UnsafeRedirectError</code> error.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="n">params</span><span class="o">[</span><span class="ss">:redirect_url</span><span class="o">]</span></code></pre>
<p>If you intend to redirect to an external site, and you’re certain the destination is safe, you can explicitly opt into it:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to</span> <span class="s2">&#34;https://rubyonrails.org&#34;</span><span class="p">,</span> <span class="ss">allow_other_host</span><span class="p">:</span> <span class="kp">true</span></code></pre>
<p>This bypasses the open redirect protection, but should be used with caution. If the URL comes from user input, it’s better to validate it against an allowlist or redirect to a known fallback.</p>
<h3 id="redirect-users-back-to-where-they-came-from">Redirect Users Back to Where They Came From</h3>
<p>Sometimes, you want to to return users to the page they were previously on, especially after performing an action like signing in, submitting a form, or dismissing a modal. Rails provides a built-in helper method for this purpose: <a href="https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_back_or_to"><code>redirect_back_or_to</code></a>.</p>
<p>This method attempts to redirect the user to the referrer (i.e., the page that linked to the current request). If that information is unavailable, either due to browser privacy settings, security policies, or the request simply lacking the <code>Referer</code> header, then Rails will instead redirect to a specified fallback location.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_back_or_to</span><span class="p">({</span> <span class="ss">action</span><span class="p">:</span> <span class="s2">&#34;show&#34;</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="mi">5</span> <span class="p">})</span>
<span class="n">redirect_back_or_to</span> <span class="vi">@post</span>
<span class="n">redirect_back_or_to</span> <span class="s2">&#34;http://www.rubyonrails.org&#34;</span>
<span class="n">redirect_back_or_to</span> <span class="s2">&#34;/images/screenshot.jpg&#34;</span>
<span class="n">redirect_back_or_to</span> <span class="n">posts_url</span>
<span class="n">redirect_back_or_to</span> <span class="nb">proc</span> <span class="p">{</span> <span class="n">edit_post_url</span><span class="p">(</span><span class="vi">@post</span><span class="p">)</span> <span class="p">}</span>
<span class="n">redirect_back_or_to</span> <span class="s1">&#39;/&#39;</span><span class="p">,</span> <span class="ss">allow_other_host</span><span class="p">:</span> <span class="kp">false</span></code></pre>
<p><strong>How It Works</strong></p>
<p>Under the hood, <code>redirect_back_or_to</code> checks the <code>Referer</code> header (<code>request.referer</code>). If that value is present and considered safe, it issues a redirect to it. Otherwise, it falls back to the location you provide.</p>
<p>Modern browsers may omit the <code>Referer</code> header in certain cases. For example, if the navigation was triggered by a cross-origin request. Because of this, always supply a reliable fallback.</p>
<hr>
<h2 id="under-the-hood-how-redirect_to-method-works">Under the Hood: How redirect_to Method Works</h2>
<p>Here’s the source code for the <a href="https://github.com/rails/rails/blob/4b7fb1d14b954d2348d2065ff955466479509656/actionpack/lib/action_controller/metal/redirecting.rb#L103"><code>redirect_to</code></a> method:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">redirect_to</span><span class="p">(</span><span class="n">options</span> <span class="o">=</span> <span class="p">{},</span> <span class="n">response_options</span> <span class="o">=</span> <span class="p">{})</span>
  <span class="k">raise</span> <span class="no">ActionControllerError</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;Cannot redirect to nil!&#34;</span><span class="p">)</span> <span class="k">unless</span> <span class="n">options</span>
  <span class="k">raise</span> <span class="no">AbstractController</span><span class="o">::</span><span class="no">DoubleRenderError</span> <span class="k">if</span> <span class="n">response_body</span>

  <span class="n">allow_other_host</span> <span class="o">=</span> <span class="n">response_options</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="ss">:allow_other_host</span><span class="p">)</span> <span class="p">{</span> <span class="n">_allow_other_host</span> <span class="p">}</span>

  <span class="n">proposed_status</span> <span class="o">=</span> <span class="n">_extract_redirect_to_status</span><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">response_options</span><span class="p">)</span>

  <span class="n">redirect_to_location</span> <span class="o">=</span> <span class="n">_compute_redirect_to_location</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">options</span><span class="p">)</span>
  <span class="n">_ensure_url_is_http_header_safe</span><span class="p">(</span><span class="n">redirect_to_location</span><span class="p">)</span>

  <span class="nb">self</span><span class="o">.</span><span class="n">location</span>      <span class="o">=</span> <span class="n">_enforce_open_redirect_protection</span><span class="p">(</span><span class="n">redirect_to_location</span><span class="p">,</span> <span class="ss">allow_other_host</span><span class="p">:</span> <span class="n">allow_other_host</span><span class="p">)</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">response_body</span> <span class="o">=</span> <span class="s2">&#34;&#34;</span>
  <span class="nb">self</span><span class="o">.</span><span class="n">status</span>        <span class="o">=</span> <span class="n">proposed_status</span>
<span class="k">end</span></code></pre>
<p>As you can see, it raises an error if you pass <code>nil</code> or if a response was already set, preventing you from sending two responses (e.g., calling <code>render</code> and then <code>redirect_to</code> in the same action).</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">raise</span> <span class="no">ActionControllerError</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&#34;Cannot redirect to nil!&#34;</span><span class="p">)</span> <span class="k">unless</span> <span class="n">options</span>
<span class="k">raise</span> <span class="no">AbstractController</span><span class="o">::</span><span class="no">DoubleRenderError</span> <span class="k">if</span> <span class="n">response_body</span></code></pre>
<p>Then it determines if it's safe to redirect to a URL on a different host. This is part of open redirect protection (default is <strong>not</strong> allowed unless explicitly permitted).</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">allow_other_host</span> <span class="o">=</span> <span class="n">response_options</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="ss">:allow_other_host</span><span class="p">)</span> <span class="p">{</span> <span class="n">_allow_other_host</span> <span class="p">}</span></code></pre>
<p>Next, it figures out the HTTP status code for the redirect, like <code>302</code>, <code>303</code>, or <code>307</code>, using provided options or defaults.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">proposed_status</span> <span class="o">=</span> <span class="n">_extract_redirect_to_status</span><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">response_options</span><span class="p">)</span></code></pre>
<p>Converts <code>options</code> into a full URL string. For example:</p>
<ul>
<li><code>redirect_to post_path(@post)</code> → <code>&quot;/posts/123&quot;</code></li>
<li><code>redirect_to &quot;https://example.com&quot;</code> → same string</li>
</ul>
<p>It also sanitizes the location to ensure it can safely be included in the HTTP <code>Location</code> header without causing malformed responses.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">redirect_to_location</span> <span class="o">=</span> <span class="n">_compute_redirect_to_location</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">options</span><span class="p">)</span>
<span class="n">_ensure_url_is_http_header_safe</span><span class="p">(</span><span class="n">redirect_to_location</span><span class="p">)</span></code></pre>
<p>Then it sets the <code>Location</code> header based on the URL, route, or options you pass in. Additionally, it also ensures that the redirect is either:</p>
<ul>
<li>within the same host (<code>allow_other_host: false</code>), or</li>
<li>explicitly allowed (<code>allow_other_host: true</code>)</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="nb">self</span><span class="o">.</span><span class="n">location</span> <span class="o">=</span> <span class="n">_enforce_open_redirect_protection</span><span class="p">(</span><span class="n">redirect_to_location</span><span class="p">,</span> <span class="ss">allow_other_host</span><span class="p">:</span> <span class="n">allow_other_host</span><span class="p">)</span></code></pre>
<p>Finally, it sets the response to be empty (<code>&quot;&quot;</code>) because browsers don’t care about the body for redirects. It also applies the HTTP status (<code>302 Found</code> by default).</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="nb">self</span><span class="o">.</span><span class="n">response_body</span> <span class="o">=</span> <span class="s2">&#34;&#34;</span>
<span class="nb">self</span><span class="o">.</span><span class="n">status</span>        <span class="o">=</span> <span class="n">proposed_status</span></code></pre>
<p>The heavy lifting is done by <code>_compute_redirect_to_location</code>, which supports the different formats Rails allows: strings, symbols, hashes, route helpers, or full URLs.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">_compute_redirect_to_location</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">options</span><span class="p">)</span>
  <span class="k">case</span> <span class="n">options</span>
  <span class="c1"># The scheme name consist of a letter followed by any combination of letters,</span>
  <span class="c1"># digits, and the plus (&#34;+&#34;), period (&#34;.&#34;), or hyphen (&#34;-&#34;) characters; and is</span>
  <span class="c1"># terminated by a colon (&#34;:&#34;). See</span>
  <span class="c1"># https://tools.ietf.org/html/rfc3986#section-3.1 The protocol relative scheme</span>
  <span class="c1"># starts with a double slash &#34;//&#34;.</span>
  <span class="k">when</span> <span class="sr">/\A([a-z][a-z\d\-+.]*:|\/\/).*/i</span>
    <span class="n">options</span><span class="o">.</span><span class="n">to_str</span>
  <span class="k">when</span> <span class="nb">String</span>
    <span class="n">request</span><span class="o">.</span><span class="n">protocol</span> <span class="o">+</span> <span class="n">request</span><span class="o">.</span><span class="n">host_with_port</span> <span class="o">+</span> <span class="n">options</span>
  <span class="k">when</span> <span class="no">Proc</span>
    <span class="n">_compute_redirect_to_location</span> <span class="n">request</span><span class="p">,</span> <span class="nb">instance_eval</span><span class="p">(</span><span class="o">&amp;</span><span class="n">options</span><span class="p">)</span>
  <span class="k">else</span>
    <span class="n">url_for</span><span class="p">(</span><span class="n">options</span><span class="p">)</span>
  <span class="k">end</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="s2">&#34;</span><span class="se">\0\r\n</span><span class="s2">&#34;</span><span class="p">)</span>
<span class="k">end</span></code></pre>
<p>I think it's pretty self-explanatory.</p>
<p><strong>Here's your challenge:</strong> Take a look at the <a href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for">API documentation for the <code>url_for</code> method</a> and try to understand how it works. Pay attention to the different types of arguments it accepts and the various ways you can use it in a Rails application.</p>

</div>
]]></content:encoded><pubDate>Sat, 07 Jun 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/redirects-in-rails</link><guid isPermaLink="true">https://writesoftwarewell.com/redirects-in-rails</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Understanding the Render Method in Rails</title><description>In this post, we'll learn how Rails' render method works and how to use it effectively. From rendering templates, partials, and inline content to JSON and custom status codes, this post explores the different ways to render views from your controllers.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <blockquote>
<p>This is the sixth post in the series on <a href="https://writesoftwarewell.com/tag/controllers">Rails controllers</a>.</p>
</blockquote>
<p>When building Rails apps, we often take <code>render</code> for granted. It’s easy to let Rails implicitly render the default template or to drop in <code>render :new</code> to render a different template.</p>
<p>However, as you get deeper into Rails, you learn that there’s a lot more under the hood: whether you want to render JSON APIs, partials, custom inline ERB, or raw files, the <code>render</code> method is one of the most flexible and powerful tools in the Rails controller toolbox.</p>
<p>Let’s explore the various ways to use <code>render</code> in controller actions, starting from the basics, and then venturing into the lesser-known territory. Knowing all the ways <code>render</code> works helps you build better controllers, whether you’re building HTML pages, APIs, or admin panels. Once you’ve mastered the render API, you can keep your controllers focused, your templates clean, and your responses accurate.</p>
<p><em>This post focuses on the external API of the</em> <em><code>render</code></em> <em>method. If you're curious about how it works behind the scenes by reading the Rails source code, check out this post:</em> <a href="https://writesoftwarewell.com/rails-rendering-process">Understanding the Rails Rendering Process</a></p>
<h2 id="default-behavior-rendering-the-actions-view">Default Behavior: Rendering the Action's View</h2>
<p>In the controller actions, if you don't explicitly render, Rails will render the template with the name matching the name of the controller action. This is the most common case, and Rails handles it implicitly.</p>
<p>For example, if you have this controller:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">class</span> <span class="nc">PostsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
  <span class="k">def</span> <span class="nf">index</span>
    <span class="vi">@posts</span> <span class="o">=</span> <span class="no">Post</span><span class="o">.</span><span class="n">all</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Rails will render the <code>app/views/posts/index.html.erb</code> view template, without you having to explicitly render anything. In fact, the <code>index</code> action is not even needed, and Rails will assume it by default.</p>
<p>This is one of the best examples of convention over configuration, a core principle of the Rails framework. This is the sort of magic people talk about when they say Rails is magic.</p>
<p>If you do want to be explicit, pass the name of the action as a symbol:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">:index</span></code></pre>
<p>A common use case is when the validation fails during a create action, and we need to re-render the form using the new action.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">create</span>
  <span class="vi">@post</span> <span class="o">=</span> <span class="no">Post</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">post_params</span><span class="p">)</span>

  <span class="k">if</span> <span class="vi">@post</span><span class="o">.</span><span class="n">save</span>
    <span class="n">redirect_to</span> <span class="vi">@post</span><span class="p">,</span> <span class="ss">notice</span><span class="p">:</span> <span class="s2">&#34;Post was successfully created.&#34;</span>
  <span class="k">else</span>
    <span class="n">render</span> <span class="ss">:new</span><span class="p">,</span> <span class="ss">status</span><span class="p">:</span> <span class="ss">:unprocessable_entity</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>Remember that we're not redirecting to the <code>new</code> action above. The code under the <code>new</code> method won't be executed. We're simply rendering the <code>new</code> template.</p>
<p>You can also render another format like <code>.json.erb</code>:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">:index</span><span class="p">,</span> <span class="ss">formats</span><span class="p">:</span> <span class="ss">:json</span></code></pre>
<p><strong>Note:</strong> Calling the render method doesn't magically halt execution of your controller's action method. Rails will throw the <code>DoubleRenderError</code> if render in the middle of the action without returning explicitly.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">show</span>
  <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
  
  <span class="k">if</span> <span class="vi">@book</span><span class="o">.</span><span class="n">special?</span>
    <span class="n">render</span> <span class="ss">action</span><span class="p">:</span> <span class="s2">&#34;special_show&#34;</span>
  <span class="k">end</span>
  
  <span class="n">render</span> <span class="ss">action</span><span class="p">:</span> <span class="s2">&#34;regular_show&#34;</span>
<span class="k">end</span></code></pre>
<p>If you don't want to execute the rest of the code that follows, return early.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="k">def</span> <span class="nf">show</span>
  <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
  
  <span class="k">if</span> <span class="vi">@book</span><span class="o">.</span><span class="n">special?</span>
    <span class="n">render</span> <span class="ss">action</span><span class="p">:</span> <span class="s2">&#34;special_show&#34;</span>
    <span class="k">return</span>
  <span class="k">end</span>
  
  <span class="n">render</span> <span class="ss">action</span><span class="p">:</span> <span class="s2">&#34;regular_show&#34;</span>
<span class="k">end</span></code></pre>
<p>If you want to see the exact output of the <code>render</code> method, call the <code>render_to_string</code> method. It uses the same options as the <code>render</code> method but returns the string result without sending response back to the server.</p>
<h2 id="render-a-template-from-another-controller">Render a Template from Another Controller</h2>
<p>To render a view template from another controller, you can specify the full path to the template using the <code>render</code> method. For example:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="c1"># app/controllers/orders_controller.rb</span>

<span class="k">class</span> <span class="nc">OrdersController</span>
  <span class="k">def</span> <span class="nf">show_summary</span>
    <span class="vi">@order</span> <span class="o">=</span> <span class="no">Order</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
    <span class="n">render</span> <span class="ss">template</span><span class="p">:</span> <span class="s2">&#34;invoices/summary&#34;</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
<p>This will render the <code>app/views/invoices/summary.html.erb</code> template, even though the action is in <code>OrdersController</code>. The path is relative to <code>app/views</code>, without the file extension.</p>
<p>If you want, you can also specify a full path to a template in a different controller:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="s2">&#34;admin/dashboard/show&#34;</span></code></pre>
<p>Rails will look for <code>app/views/admin/dashboard/show.html.erb</code>.</p>
<h2 id="rendering-text-html-json-and-xml">Rendering Text, HTML, JSON, and XML</h2>
<p>When building APIs or responding with simple messages, you often need to render raw content. You can do this using the <code>plain</code>, <code>html</code>, <code>json</code>, or <code>xml</code> options to the <code>render</code> method.</p>
<p><strong>Text</strong></p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">plain</span><span class="p">:</span> <span class="s2">&#34;Not authorized&#34;</span><span class="p">,</span> <span class="ss">status</span><span class="p">:</span> <span class="ss">:unauthorized</span></code></pre>
<p>When using the <code>:plain</code> option, the text is rendered without the layout. If you want to use the layout, add the <code>layout: true</code> option and create the layout file <code>.text.erb</code> extension.</p>
<p><strong>HTML</strong></p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">html</span><span class="p">:</span> <span class="s2">&#34;&lt;strong&gt;Saved!&lt;/strong&gt;&#34;</span><span class="o">.</span><span class="n">html_safe</span></code></pre>
<p><strong>JSON</strong></p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">json</span><span class="p">:</span> <span class="vi">@user</span></code></pre>
<p>Note, the argument (@user above) must respond to <code>to_json</code>. The <code>render</code> method automatically calls <code>to_json</code> for you.</p>
<p>Or, customize the output:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">json</span><span class="p">:</span> <span class="p">{</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="nb">name</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span> <span class="p">}</span></code></pre>
<p>If you want to explore the Rails internals to understand how it really works, check out this post.</p>
<p><a href="https://writesoftwarewell.com/rails-rendering-process">Understanding the Rails Rendering Process</a></p>
<p><strong>XML</strong></p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">xml</span><span class="p">:</span> <span class="vi">@user</span></code></pre>
<p>Same with JSON, the <code>render</code> method will call <code>to_xml</code> for you.</p>
<h2 id="rendering-raw-file-or-binary-data">Rendering Raw File or Binary Data</h2>
<p>If you want to send a file to the client (such as a static page), Rails can render a raw file from an absolute path.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">file</span><span class="p">:</span> <span class="no">Rails</span><span class="o">.</span><span class="n">root</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s1">&#39;public/terms.html&#39;</span><span class="p">)</span></code></pre>
<p>Make sure you don't use user-provided inputs otherwise it can be used to access sensitive files in your app.</p>
<p>By default, this renders as HTML. If you want to serve it as text:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">render</span> <span class="ss">file</span><span class="p">:</span> <span class="no">Rails</span><span class="o">.</span><span class="n">root</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s1">&#39;public/data.csv&#39;</span><span class="p">),</span> <span class="ss">content_type</span><span class="p">:</span> <span class="s1">&#39;text/csv&#39;</span></code></pre>
<h3 id="binary-content">Binary content</h3>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">send_data</span> <span class="n">image_data</span><span class="p">,</span> <span class="ss">type</span><span class="p">:</span> <span class="s1">&#39;image/png&#39;</span><span class="p">,</span> <span class="ss">disposition</span><span class="p">:</span> <span class="s1">&#39;inline&#39;</span></code></pre>
<p>Or for file downloads:</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">send_file</span> <span class="s1">&#39;/path/to/file.pdf&#39;</span><span class="p">,</span> <span class="ss">type</span><span class="p">:</span> <span class="s1">&#39;application/pdf&#39;</span><span class="p">,</span> <span class="ss">disposition</span><span class="p">:</span> <span class="s1">&#39;attachment&#39;</span></code></pre>
<p>Technically not <code>render</code>, but still part of controller response APIs. If you don't need to provide the layout, <code>send_file</code> is often a faster and better option.</p>
<h3 id="rendering-nothing">Rendering Nothing</h3>
<p>Sometimes, you don't want to render any body, but just want to send a header. In this case, you can use the <code>head</code> method, passing the HTTP status code.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">head</span> <span class="ss">:ok</span>

<span class="c1"># OR</span>

<span class="n">head</span> <span class="ss">:unauthorized</span></code></pre>
<h2 id="options-available-to-render">Options Available to Render</h2>
<p>Here’s a summary of the common options you can pass to <code>render</code>:</p>
<p><strong>Rendering mode</strong></p>
<ul>
<li><strong><code>:partial</code></strong> – Renders a partial.</li>
<li><strong><code>:inline</code></strong> – Renders an inline string of ERB.</li>
<li><strong><code>:file</code></strong> – Renders a file from disk.</li>
<li><strong><code>:body</code></strong> – Returns a raw string as the response body.</li>
<li><strong><code>:plain</code></strong> – Renders plain text.</li>
<li><strong><code>:html</code></strong> – Renders raw HTML (you must mark it <code>html_safe</code>).</li>
<li><strong><code>:json</code></strong> – Renders JSON (calls <code>to_json</code> on object).</li>
<li><strong><code>:xml</code></strong> – Renders XML (calls <code>to_xml</code>).</li>
<li><strong><code>:js</code></strong> – Renders JavaScript.</li>
</ul>
<p><strong>Options</strong></p>
<ul>
<li><strong><code>:content_type</code></strong> – Overrides the MIME type.</li>
<li><strong><code>:assigns</code></strong> – Provides the hash of instance variable assignments for the template.</li>
<li><strong><code>:locals</code></strong> – Provides the hash of local variable assignments for the template.</li>
<li><strong><code>:layout</code></strong> - Specify a different layout or render without a layout with <code>layout: false</code>.</li>
<li><strong><code>:location</code></strong> – Sets the <code>Location</code> header. Often used with <code>status: :found</code>.</li>
<li><strong><code>:status</code></strong> – Sets the HTTP status code (e.g. <code>:ok</code>, <code>:not_found</code>).</li>
<li><strong><code>:template</code></strong> – Renders a specific template file.</li>
<li><strong><code>:action</code></strong> – Renders a different action’s view in the same controller.</li>
<li><strong><code>:formats</code></strong> – Change the default format specified in the request (<code>:html</code> by default)</li>
<li><strong><code>:variants</code></strong> – Look for template variations of the same format.</li>
</ul>
<p>Before rendering, Rails looks at the action name, locale, format, variant, etc. to figure out exactly what to render. If a template doesn't exist, or is not in the correct format or variant, Rails will raise the <code>ActionController::UnknownFormat</code> error and render <code>204 No Content</code>.</p>
<p>You don’t need to use all these variations daily, but knowing they exist gives you tools for every situation.</p>
<h2 id="render-to-string">Render to String</h2>
<p>Sometimes you want to use your view rendering engine to generate a string, without actually sending it as a response. That’s what <code>render_to_string</code> is for.</p>
<p>Common use cases include:</p>
<ul>
<li>Sending HTML or text emails using the same templates as your web views.</li>
<li>Generating a downloadable PDF from a view.</li>
<li>Logging or caching the rendered output.</li>
</ul>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="n">html</span> <span class="o">=</span> <span class="n">render_to_string</span><span class="p">(</span><span class="ss">template</span><span class="p">:</span> <span class="s2">&#34;invoices/show&#34;</span><span class="p">,</span> <span class="ss">layout</span><span class="p">:</span> <span class="kp">false</span><span class="p">)</span>
<span class="no">PdfService</span><span class="o">.</span><span class="n">generate</span><span class="p">(</span><span class="n">html</span><span class="p">)</span></code></pre>
<p>Keep in mind that <code>render_to_string</code> still runs the full view rendering stack (layouts, helpers, partials), so it’s not free performance-wise, but it's often the cleanest way to reuse your existing views.</p>
<h2 id="rendering-partials-with-collections">Rendering Partials with Collections</h2>
<p>Rendering collections is a performance-friendly way to output many items using a single partial. If you’re not using it yet, you should.</p>
<pre data-language="ruby"><code class="code-inline language-ruby"><span class="o">&lt;%=</span> <span class="n">render</span> <span class="ss">partial</span><span class="p">:</span> <span class="s2">&#34;posts/post&#34;</span><span class="p">,</span> <span class="ss">collection</span><span class="p">:</span> <span class="vi">@posts</span> <span class="o">%&gt;</span></code></pre>
<p>Rails will call <code>_post.html.erb</code> for each item in <code>@posts</code>, assigning each one to a <code>post</code> local.</p>

</div>
]]></content:encoded><pubDate>Thu, 05 Jun 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/rails-render-method</link><guid isPermaLink="true">https://writesoftwarewell.com/rails-render-method</guid><author>akshay@typeangle.com (Akshay Khot)</author></item><item><title>Vibe Learning is Underrated</title><description>Last week, I used AI to finally learn the basics of QuickBooks and handle my company’s bookkeeping. AI didn’t just help me finish a chore, it taught me a skill I’d been avoiding for years. When used with intent, the modern AI tools can accelerate your learning in surprising ways.</description><content:encoded><![CDATA[<div class="lexxy-content syntax-theme-github-dark">
  <p><strong>Vibe coding is overrated. Vibe learning, on the other hand, is so underrated.</strong></p>
<p>I’ve always wanted to learn the basics of bookkeeping so I could manage the finances for my company, or at least, stay on top of what's going on financially.</p>
<p>I had tried a couple of times in the past, opened up QuickBooks, clicked around, got confused, and gave up. Always felt like too much for what I was trying to do. I also took a few courses and read books, but they quickly got too complex and overwhelming, and I ended up not finishing any of them. The jargon always threw me off.</p>
<p>Finally, I ended up working with a professional CPA and decided bookkeeping was not for me. </p>
<p>Last weekend, after listening to a Berkshire Hathaway annual meeting recording and hear Warren Buffett talk again and again about the importance of learning the language of accounting, I decided to give it another try.</p>
<p>However, this time I tried a different approach. I signed up for the QuickBooks premium, opened my bank accounts on one screen, and kept ChatGPT open on the other.</p>
<p>I asked ChatGPT to walk me through the QuickBooks interface: what is important, what doesn’t, what to focus on first. I linked my accounts and imported all transactions. Then started categorizing transactions. I didn't even know what categorizing a transaction in QB meant. Again, ChatGPT to the rescue.</p>
<p>From there, it was all just-in-time learning. <a href="https://headrush.typepad.com/creating_passionate_users/2005/03/motivated_to_le.html">As Kathy Sierra puts it</a>, learn only what you need to keep going, right when you need it.</p>
<p>Every time I hit a roadblock, or came across an unfamiliar term e.g. What’s a chart of accounts? What’s the difference between an expense and a bill? How should I categorize shareholder loans? What is a shareholder loan? I asked. And every time, I got real help that actually helped me keep going.</p>
<p>The great thing was how well it handled context. I described the specifics of my situation, like how some payments were split, how my accounts were structured, international payments, paying to sub-contractors, which expenses are deductible and which weren't, or how I was treating certain international family transfers and it tailored its answers accordingly. The guidance wasn’t generic. It responded as if it understood exactly what I needed, and showed me how to proceed.</p>
<p><strong>It felt like having a calm, senior bookkeeper sitting beside me, answering everything without judgment and with infinite patience.</strong></p>
<p>In about six hours, I had categorized hundreds of transactions (and created rules for future transactions). A task I’d been procrastinating on for months and months was done in a single day.</p>
<p>More importantly, I now feel comfortable handling the basics of bookkeeping. QuickBooks doesn't scare me no more. I know what a journal entry is. I understand how the chart of accounts works. I know how to generate a balance sheet, profit and loss report, and how to spot if something’s off.</p>
<p>I’m under no illusion that I’ve become a bookkeeper overnight. But compared to just a day before, a lot of the known unknowns are now known. I feel like I have a clear path to keep moving forward. I know what I don’t know, and I know how to keep learning.</p>
<p><strong>Unexpected bonus:</strong> I came away with a deeper appreciation for QuickBooks. I used to think it was a complex, clunky, and bloated piece of software and didn’t really understand why any sane accountant would prefer it over something simple with beautiful UI like <a href="https://www.waveapps.com/">Wave accounting</a> software. But I learned the true power of QuickBooks after I had finished categorizing all the transactions.</p>
<p>QuickBooks gives you a proper, structured view of your business. Once everything is categorized correctly, it becomes a dashboard for financial clarity. You want to know how much you spent on software last quarter? Or what your profit margin is this year? Just run a report and everything is there.</p>
<p>The next day, I shared my work with my real accountant / CPA, who after examining it said that everything looked good. That felt really great.</p>
<p>This whole experience has made me realize how powerful just-in-time learning can be when you combine curiosity with a knowledgeable and patient mentor. I would have never gotten through QuickBooks without ChatGPT. But with it, I didn’t just finish a chore, I gained a new skill. And this is just the beginning. I plan to go beyond the basics and keep learning more advanced stuff.</p>
<blockquote>
<p>Once you have this experience, it's like a whole new part of the brain unlocks. Skills that used to feel inaccessible suddenly seem within reach. Not just software skills like writing better SQL and systems programming, but also skills like photo and video editing or graphic design, doing serious work in Excel spreadsheets, editing video, automating parts of your workflow, understanding legal contracts, interpreting financial statements and metrics, and so on.</p>
</blockquote>
<p><strong>I'm not talking about mastery here.</strong> That takes real time, years of practice and dedicated study. But these are practical skills, learning even the basics will make you sharper, faster, and more independent in your work. And you can always pursue the path of mastery if you choose to. Learning with AI makes it much easier to get started.</p>
<p>In the early '80s, Steve Jobs described the personal computer as a bicycle for the mind. With AI (ChatGPT, Cursor, etc.), I finally understand what that feels like.</p>

</div>
]]></content:encoded><pubDate>Tue, 27 May 2025 00:00:00 +0000</pubDate><link>https://writesoftwarewell.com/vibe-learning-is-underrated</link><guid isPermaLink="true">https://writesoftwarewell.com/vibe-learning-is-underrated</guid><author>akshay@typeangle.com (Akshay Khot)</author></item></channel></rss>