<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by William Fischer on Medium]]></title>
        <description><![CDATA[Stories by William Fischer on Medium]]></description>
        <link>https://medium.com/@william.fischer?source=rss-edd0b386c9b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fFJNW8NTY1VjKO44heuksg.png</url>
            <title>Stories by William Fischer on Medium</title>
            <link>https://medium.com/@william.fischer?source=rss-edd0b386c9b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:16:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@william.fischer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Aliasing and Chaining Relationships]]></title>
            <link>https://medium.com/@william.fischer/aliasing-and-chaining-relationships-80040f222060?source=rss-edd0b386c9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/80040f222060</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[wizards]]></category>
            <category><![CDATA[activerecord]]></category>
            <dc:creator><![CDATA[William Fischer]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 21:09:08 GMT</pubDate>
            <atom:updated>2018-11-07T22:36:16.199Z</atom:updated>
            <content:encoded><![CDATA[<h4>ActiveRecord Wizardry in Rails</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jy3tWAAyINCd5CcGw4u1dQ.png" /><figcaption>Image by <a href="https://dribbble.com/shots/3182998-Pixel-Wizard">Razvan Vezeteu</a></figcaption></figure><p>If programming frameworks were fictional characters, Ruby on Rails would be Gandalf. Not only because it’s completely magical — it also works in mysterious ways. While you’re trying to make it to Bree without being decapitated by a handful of dead guys in 400 year old bath-robes (or at least trying to make your tests pass), Rails (Gandalf) is off in far-away lands setting the stage for the rest of your journey.</p><p>Even if that is the worst metaphor since “An Ogre is like an onion” (I’m a programmer, for god’s sake), the point remains that Rails does a lot of work for you, and sometimes it can be a struggle to get a grip on what just happened.</p><p>It’s no secret that rails can make it very easy (sometimes <em>too</em> easy) to build an MVC web application. Rails generators, ActiveRecord, and an unlimited supply of awesome gems give you everything you need to get up and running. ActiveRecord in particular simplifies model creation and database interactions. One way to take advantage of this power is to use aliases and through relationships to easily navigate “circular” database schemas using Rails helper methods.</p><p>To illustrate the concept (and stick with the theme), we’ll build out an example revolving around basic spell-craft. Let’s break it down.</p><p>To start, a wizard can know many spells, and a spell can be learned by many wizards. So we’ll have a table for spells, one for wizards, and a join table between the two. The convention in Rails is to name a joins table like this one something like wizard_spells, but we’re going to give it a more meaningful title</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2MVXIecvV0b-Pvu6HR5QA.png" /><figcaption>Wizards &amp; Spells Schema</figcaption></figure><p>Now, suppose we also want to track the spells that have been cast, and we’re particularly interested in Wizard Duals. That means a wizard can cast a spell, or be targeted by one. We can’t use the spells table for this one, because it doesn’t provide any way of keeping track of the caster. Instead, we’ll want another joins table, this time between known_spells and wizards called cast_spells . At this point, our schema will look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZpposAddfWSzvTKZ5-qTA.png" /></figure><p>If that’s not a twisted mess, I don’t know what is. It seems like it would be hopeless to ask our database for the names of all the wizards Harry Potter cast “expelliarmus” on, as well as all the wizards who cast the same spell on Neville Longbottom, using rails generated helpers instead of hand-rolled ActiveRecord joins.</p><p>That, however, is exactly what we’re about to do.</p><p>First, lets create our main tables using all the magic of rails at our disposal. Using generators, we’ll start by building out our basic migrations and models.</p><pre>&gt; rails generate model wizard name:string<br>&gt; rails generate model spell incantation:string</pre><p>Model generators create the model files, test files, and corresponding migrations. Let’s run rake db:{create,migrate} to apply the migration, then we’ll turn to our joins table.</p><p>From here we could set up a joins table using a rails migration generator. In fact, a rails generate migration command will create a joins table as long as CreateJoinTable is included in the name.</p><pre>&gt; rails generate migration CreateJoinTableWizardSpell wizard spell</pre><p>However, in our case we’re just going to make another model for several reasons.</p><ol><li>We’re using a custom name.</li><li>The primary key will be used in another joins table.</li><li>We need the model file to set up aliased relationships (more on that later).</li></ol><p>So instead of using that deceptively placed migration generator above, let’s do this…</p><pre>&gt; rails generate model known_spell spell:references wizard:references</pre><p>At this point, we’ll have our 3 models, and the ‘joins’ table will have belongs_to relationships with it’s counterparts, wizard and spell. We’ll also have to add the has_many relationships.</p><pre>class Spell &lt; ApplicationRecord<br>  has_many :known_spells<br>end<br>...<br>class Wizard &lt; ApplicationRecord<br>  has_many :known_spells<br>end</pre><p>And finally, we add our through relationship, which allows us to “reach” through the joins table from either side. The following will allow us to use the convenience method wizard.spells (assuming wizard is a Wizard )</p><pre>class Wizard &lt; ApplicationRecord<br>  has_many :known_spells<br>  has_many spells, through: :known_spells<br>end</pre><p><em>“But what about </em><em>spell.wizards?” — You, just now</em></p><p>To that I ask, do you want to know about the wizards that a spell has <em>hit, </em>or the wizards who have cast it? Because that, my friends, makes all the difference. But before we jump into that, let’s build out the last piece of our schema.</p><pre>&gt; rails generate model cast_spell known_spell:references wizard:references</pre><p>And, of course, we’ll also have to throw in a has_many :cast_spells in our KnownSpell model.</p><p>Here’s the tricky part. Right now, a CastSpell model object belongs_to a wizard . That means that cast_spell.wizard will produce the “owner” of that spell, in the belongs_to sense. But that’s not at all intuitive, since in this case, the wizard in question is the <em>target</em> of the spell, not the caster. On the contrary, we would definitely want it to return the contents of cast_spell.known_spell.wizard , and cast_spell.known_spell.spell to return the spell. All of this is more than a little clunky, but lets see what we can do.</p><p>First, let’s make cast_spell.victim return the wizard whom the spell struck.</p><pre>class CastSpell &lt; ApplicationRecord<br>  belongs_to :known_spell<br>  belongs_to :victim, class_name: :Wizard, foreign_key: &quot;wizard_id&quot;<br>end</pre><p>This associates the Wizard model and the wizard_id foreign key with the aliased helper method victim .</p><p>The coolest part is, now that CastSpell has a victim relationship, any other class that has a relationship <em>with </em>CastSpell can access that same relationship through it. For example, a Wizard might have_many :cast_spells through: :known_spells , which means he can also have_many :victims, through: :cast_spells .</p><p>We can see now that these chains and aliases allow us to actually trace our way <em>around </em>the circular schema without ever losing what exactly we’re talking about. This gives us a way of creating an intuitive interface for our databases, where we access entries not just based on the names of the tables, but on the <em>nature of the relationships between them.</em></p><p>On top of that, there’s very little overhead in setting up these helper methods, so we can make chain through using different names so we can access it using intuitive language later on. For example, maybe a “spell” shouldn’t have a “victim.” A <em>spell</em> is impersonal. It doesn’t <em>intend</em> anything. But it <em>does</em> have a target. So maybe we can call the wizard on the receiving end of a spell a target, as long as we’re “accessing” the wizard from a spell .</p><pre>class CastSpell &lt; ApplicationRecord<br>  belongs_to :known_spell<br>  belongs_to :victim,<br>             class_name: :Wizard,<br>             foreign_key: &quot;wizard_id&quot;<br>  belongs_to :target,<br>             class_name: :Wizard,<br>             foreign_key: &quot;wizard_id&quot;<br>end</pre><pre>class Spell &lt; ApplicationRecord<br>  has_many :known_spells<br>  has_many :cast_spells, through: :known_spells<br>  has_many :targets, through: :cast_spells<br>  has_many :casters, through: :known_spells<br>end</pre><p>We can apply similar approach to the rest of our models. Here’s what the final stack might look like.</p><pre>class CastSpell &lt; ApplicationRecord<br>  belongs_to :known_spell<br>  belongs_to :victim,<br>             class_name: :Wizard,<br>             foreign_key: &quot;wizard_id&quot;<br>  belongs_to :target,<br>             class_name: :Wizard,<br>             foreign_key: &quot;wizard_id&quot;<br>end</pre><pre>class KnownSpell &lt; ApplicationRecord<br>  belongs_to :spell<br>  belongs_to :caster, <br>             class_name: &#39;Wizard&#39;, <br>             foreign_key: &quot;wizard_id&quot;<br>  has_many :cast_spells<br>  has_many :victims,<br>           through: :cast_spells<br>  has_many :targets,<br>           through: :cast_spells<br>end</pre><pre>class Spell &lt; ApplicationRecord<br>  has_many :known_spells<br>  has_many :cast_spells, <br>           through: :known_spells<br>  has_many :wizards, <br>           through: :known_spells<br>  has_many :targets, <br>           through: :cast_spells<br>end</pre><pre>class Wizard &lt; ApplicationRecord<br>  has_many :known_spells<br>  has_many :spells, <br>           through: :known_spells<br>  has_many :cast_spells, <br>           through: :known_spells<br>  has_many :victims, <br>           through: :cast_spells<br>end</pre><p>Keep in mind the very real danger of over-aliasing, and making code that’s difficult to read. You probably don’t want multiple aliases in multiple places.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80040f222060" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>