<?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 Tiago Farias on Medium]]></title>
        <description><![CDATA[Stories by Tiago Farias on Medium]]></description>
        <link>https://medium.com/@tiago_farias?source=rss-8b8bbc61c455------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Wlllns4BG_7ir8Naq17Dvw.jpeg</url>
            <title>Stories by Tiago Farias on Medium</title>
            <link>https://medium.com/@tiago_farias?source=rss-8b8bbc61c455------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:48:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tiago_farias/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[Interactors in Ruby — easy as cake, simple as pie]]></title>
            <link>https://medium.com/goiabada/interactors-in-ruby-easy-as-cake-simple-as-pie-33f66de2eb78?source=rss-8b8bbc61c455------2</link>
            <guid isPermaLink="false">https://medium.com/p/33f66de2eb78</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Tiago Farias]]></dc:creator>
            <pubDate>Tue, 31 Oct 2017 18:32:17 GMT</pubDate>
            <atom:updated>2017-12-04T19:49:01.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cbwj87FhSR94uxa1fmnJ3A.jpeg" /></figure><h3><strong>Interactors in Ruby — easy as cake, simple as pie</strong></h3><p>Ugh, I hate to start an article straight with a piece of code. But, really, this is the best way to show you the problem and then a clear solution for it. So, please take a look at this controller action and see if you can spot the problem with it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39722872d2c066efeddf9de0087bc65b/href">https://medium.com/media/39722872d2c066efeddf9de0087bc65b/href</a></iframe><p>Yikes! Classic Fat Controller, right? It is initializing and saving objects, sending emails and creating async jobs. All in one method. Well, we’ve been hearing for a long time now that we shouldn’t be imposing our little methods/classes too many responsibilities, otherwise they could grow up and become sociopaths. Imagine if later on we found out that this controller action needs to validate a couple parameters to decide if the object will be persisted on the database. Well, obviously more code is going to be needed no matter what you do. But does it need to be right there in our already bloated method? “Oh yeah, I’m much better off handling business logic inside my Models, since it’s all there anyway, the queries, the scopes, callbacks, etc.” No, wait, what? Not 2010 anymore?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkVCmrqWuZxIUVEMphhDRQ.jpeg" /></figure><h3><strong>Interactor to the rescue</strong></h3><p>Here’s where the Interactor Design Pattern shines with flying colors. Basically, an Interactor is an object that encapsulates business logic (read domain models) for one (and one only) use case. That’s it. It solves one problem for a small part of the domain of the application. It is based on the Command pattern, where each Command class/object represents a task and has one public method. Basically, something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c398d5c2187ec2cdf1c871883e5f9e3b/href">https://medium.com/media/c398d5c2187ec2cdf1c871883e5f9e3b/href</a></iframe><p>I know, it was a very simplistic definition of the Command pattern. Well, <a href="https://sourcemaking.com/design_patterns/command">here</a> you can find a more formal definition with more examples in case you got curious. But you got the main idea: Interactor is basically a Command object that we can use to reduce bloat in our controllers and models. Service Object is yet another name for it, even though it’s quite general. I mean, there is no clear pattern for it. There are some guidelines, like: “it should be a PORO (Plain Old Ruby Object)” and “try to create it with only one responsibility, if possible” or “minimal public API”, but nothing really enforces it. Having said that, I’ve seen Service Objects with more than one method in their public APIs and, you know what? They were pretty good looking.</p><p>By the way, the TrailBlazer framework (which sits on top of Rails) calls these objects <a href="http://trailblazer.to/gems/operation/2.0/">Operations</a>. And the dry-rb team created a DSL based on the same idea with a few more features in <a href="https://github.com/dry-rb/dry-transaction">dry-transactions</a>. But I’d like to use the example of a more popular gem for handling such objects, the <a href="https://github.com/collectiveidea/interactor">gem <strong>interactor</strong></a>. And since I’m talking about it, I’ll take the time to highlight some of its strengths and some possible improvements that I think would be feasible. Of course, it’s just my opinion, it’s not written in blood, so hold your horses =).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZJXO0PKkY_VQSmxs0AVew.gif" /></figure><h3><strong>Simple as pie</strong></h3><p>The Ruby gem Interactor solves the problem above mentioned in a very very simple way. For each use-case, action or task, whatever you may call it, you create a class named as the purpose of the task (like ReadFile, SaveUserProfile or DeleteAccount) and invoke the method call passing the data needed (or context) for that task, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee8bb7dbf26bb8c8e1c78de9ff6a3fe3/href">https://medium.com/media/ee8bb7dbf26bb8c8e1c78de9ff6a3fe3/href</a></iframe><p>Two things to setup: include the module Interactor and define a public instance method call. That’s it. This simplicity is one of the reasons I like this gem so much and we use it in many of our projects here at Guava. Besides, if we need to pre-process something before the call method, like setup or validate the arguments, we can do that with the before hook, which accepts a block as a parameter. There are also the after and around hooks.</p><p>Now let’s go back to the tasks in the first controller (the bloated one) mentioned in the beginning. Notice the create action is trying to do a list of things in order:</p><p>1. create the sale record</p><p>2. find and process the stock for the products involved</p><p>3. process and send to shipping department</p><p>4. send confirmation email</p><p>Well, to start off removing business code from our controller, we create 4 interactors: CreateSale, ProcessStock, DispatchShipping and SendConfirmationEmail. If we call each one of these interactors, it’s gonna work just fine. But there’s a caveat: if one of these operations fail, we need to rollback all the other ones already finished. Therefore, if we used this approach, we would end up with a lot of conditional code in our controller, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fbd21888cfd6ae75fac46be30c01f9f/href">https://medium.com/media/5fbd21888cfd6ae75fac46be30c01f9f/href</a></iframe><p>Not nice. In fact, it’s called conditional hell. Enter Organizers. An Organizer is a special kind of Interactor that has one responsibility: to call other interactors in a given sequence. For the situation above, we would have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c30e4a91789353a8f8fdafc8fa4c20/href">https://medium.com/media/c1c30e4a91789353a8f8fdafc8fa4c20/href</a></iframe><p>Expressive, ain’t it? It’s like, you open the PlaceOrder class and it’s right there, in simple, defined steps, basically telling you what it does. Each interactor executed passes the context (or arguments) through to the next interactor in line. So, for instance, the organizer in the example above passes only the sale (which we suppose has a lot of data about the products and stuff) as its context to the first interactor, CreateSale. But all these interactors play like a family, they share context. Meaning that if we set a variable productsin our shared context inside CreateSale, ProcessStock and the next interactors in line will all have access to products through the context object. Except if one of the interactors fail, in which case it avoids the next interactor in line of being invoked. There’s more to know in the case of a failure like the above, but I recommend reading the gem’s documentation for that.</p><p>Oh, and I did not forget about the transaction code in the bloated controller code example. I’ll talk briefly about how it can be handled in an organizer later.</p><p><a href="https://github.com/collectiveidea/interactor/pull/62">In the future</a> (probably in version 4) we may be able to pass not only interactors to the organizer to execute, but also procs and method objects! Something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/136ae0a933479ddd6d3f7fd46cfc045d/href">https://medium.com/media/136ae0a933479ddd6d3f7fd46cfc045d/href</a></iframe><p>Yeah, I think it’s cool to see organizers just receiving a Proc or Method Object and execute it while being impartial about the argument’s race, gender and nationality. We need that in the world. Also, I believe there is a use for that, for instance, if you need to create an organizer dynamically or if the task being passed is so trivial that would justify the use of a Proc (you know, because it’s a one-liner). On the other hand, I think it kinda hurts the purpose a little bit. Naming is important. Naming interactors very much so. I mean, the whole description of the task goes in the name of the class! You can read straightforward what a given interactor is all about just by reading its class name. With this idea in mind, when we read an organizer’s organize call, it becomes very clear where it’s going: CreateSale, ProcessStock, DispatchShipping, SendConfirmationEmail. Now, what if a Proc, even if it’s a one-liner, stands in the middle of the “sentence”? It’s definitely not the same as before. It’s just not as fluent, even though in more appropriate cases I guess it would still be readable. All in all, I think both arguments balance each other out, which makes me vote in favor of the change, leaving the developer responsible for the legibility of their own code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIaQCdg9Fkk1usGWV_PKzw.jpeg" /></figure><h3><strong>Sharp as a tack</strong></h3><p>There are many pearls throughout its features, but one that makes a lot of sense are its hooks: before, around and after. Think about it: this allows you to do whatever you want inside an interactor without much complexity. If you need to setup any object or validate parameters previously to your main method, you can use the before hook. To set warnings, close files or connections after the interactor successfully ran, you can use the afterhook. While around hooks allow you to weave your interactor callin between a block of code, so you can decide exactly when to invoke it. This is useful for so many times when we need to wrap our interactors with extra code. Take Rails’ ActiveRecord transactions for instance. Imagine we have a Rails app where, at some point, we need to save 3 records to a database, say, a Sale, a Stock and a Payment. The thing is: if one of them fails, we need to rollback the transaction in order to avoid inconsistent state in our database. Now, one way to do that would be to use an organizer and call an interactor for each of these tasks. But what if the third interactor, SavePayment, does not go through? We would end up with a sale that was made with no payment! Prison! Death! Or maybe just a slap on the wrist depending on the country where you’re reading this from… But, in other words, if we don’t process the 3 actions inside a single ActiveRecord transaction, we will be in trouble. That’s where the interactor’s aroundhook comes in handy, allowing us to look smarter than we really are. We can simply go with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c368ca2ebe16a06f0afd055c86b51a2/href">https://medium.com/media/9c368ca2ebe16a06f0afd055c86b51a2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6w7tFivSOPJjBW5mE3Os7A.jpeg" /></figure><h3><strong>Light as a feather</strong></h3><p>The source code of this gem is very small. Just to make a point about this, the lib folder has 5 ruby files. The longest method is 8 lines long. There are only a few conditionals and no ”elses”. Also no metaprogramming, making it very easy to understand the whole code base just by reading it, even if you don’t master ruby. And that simplicity is no coincidence, it’s by design.</p><p>For instance, there have been suggestions to implement validations inside interactors <a href="https://github.com/collectiveidea/interactor/pull/82">in the past</a>. The idea is simple: the interactor needs to validate its context before fulfilling the main task. And some spinoff gems have resulted from deep discussions about this subject, like <a href="https://github.com/jonstokes/troupe">troupe</a> for example. While I enjoy the solution and have suffered from the same kind of itch that moved this idea forward, I don’t think it goes with interactor’s philosophy. The reason is that interactor is very light, thin, with almost no magic at all, while a DSL implementation to promote context validation… y’know… not so much.</p><p>Since interactor has always been striving for simplicity and elegance from the beginning, there must be a more elegant way to provide the context validation ability without inserting too much magic in the code base. Well, I’ve been thinking that, since the context object must be self-contained, and interactor already provides beforehooks, why not just pass a validator via context and evaluate it at the beforehook of the main interactor? For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8be4e8702a84a9621138f7c4c059447/href">https://medium.com/media/c8be4e8702a84a9621138f7c4c059447/href</a></iframe><p>Notice that this idea brings up the concept of a Validation Interactor, which unsurprisingly is injected via params and validates an interactor context. It has no magic, really. In the snippet above, I present 2 ways to pass a validator to the call method. The first one would cause a change in the API, which is always harder to deal with. But it keeps context and validator as 2 separated components for the interactor to run (<em>you gotta keep’em separated</em>). The fact that there is a separated parameter for validator just makes more explicit that the validator is NOT part of the context, but another object that was injected and simply knows how to validate his brother, the context object. The second option is way simpler. The validator is part of the context and the gem needs to work a bit to pull the validator out of the context object. This also requires a better documentation, once the validator is implicit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5xiDhi4ZyCFdH4qNC_h6w.jpeg" /></figure><h3><strong>The cons</strong></h3><h4><strong>Context is global</strong></h4><p>One thing that I’ve always found kind of clumsy was the Context object passed as parameter in the callmethod. It’s basically a very promiscuous struct object, that will accept anything anytime. It is a global variable. And you know what happened to the little boy that played with global variables, right? Yeah, he died. So, stay away, please. Of course I’m exaggerating, usually there is no big problem with interactors carrying global variables around (unless you’re a purist). Often they’re short lived and the fact that they only have one single responsibility helps a lot. But I can see it getting messy. Imagine that we have an organizer of 5 interactors, each one with its own rollback hook set up. When we pass values around in a context object, with every single interactor being able to change, add or remove objects from the context object we might have a problem.</p><p>Now, if it was possible to create our own custom context class, we could decide what can be accessed or read in the context. On the other hand, if you don’t mind a global context accessed by everyone, or you don’t need one for the task you’re doing is short-lived and simple, just use the default one and you’re good to go.</p><h4><strong>Lacks a more explicit way for params validation</strong></h4><p>As explained before, there is no explicit way to validate the context object inside an interactor. The idea explained above was to use what I call a Validation Interactor. It’s a simple idea, with no dependencies and does not “stain” the philosophy behind the interactor gem whatsoever. But, as in most cases of simplicity, it may be too simple. One other solution is to go the opposite way: “pollute” the code a little bit in order to provide flexible mechanisms of context validation inside the interactor. Something along the lines of the idea of contracts, like <a href="https://github.com/michaelherold/interactor-contracts">interactor-contracts</a> and <a href="https://github.com/jonstokes/troupe">troupe</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d823e6818542a81b448164f6291db0eb/href">https://medium.com/media/d823e6818542a81b448164f6291db0eb/href</a></iframe><h3><strong>Conclusion</strong></h3><p>As we’ve seen, interactors solve a real programming problem, helping to avoid controller and model bloat. This pattern is inspired by the Command Pattern and provides a way to create an abstraction over our domain models and encapsulate business logic. That way, a lot of code manipulating our model objects, usually written inside the models or even in the controllers, can be moved to interactors, making our code more modular and DRY. In fact, here at Guava we prefer neither Fat Models nor Fat Controllers, but we favor the creation of multiple interactors whenever it’s reasonable to do so. And no, you don’t need a gem to start creating your own interactors. Remember: it’s a basic Service Object with one responsibility and one public method. Just keep it simple. On the other hand, if you feel like being guided by voices, try the interactors gem. It’s pretty neat. Very small code base, no magic, just straightforward Ruby. Also, very simple to plug into your service classes and start using. Try to make good use of its sharp features as hooks. But keep in mind that interactor has its cons as well. I mentioned some of them above, along with some techniques to go around them elegantly. Some of the problems, though, we’ll still have to wait for an official solution. Oh, well… pobody is nerfect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33f66de2eb78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goiabada/interactors-in-ruby-easy-as-cake-simple-as-pie-33f66de2eb78">Interactors in Ruby — easy as cake, simple as pie</a> was originally published in <a href="https://medium.com/goiabada">Goiabada</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To join or not to join? An act of #includes]]></title>
            <link>https://medium.com/goiabada/to-join-or-not-to-join-an-act-of-includes-f6728fcefea3?source=rss-8b8bbc61c455------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6728fcefea3</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tiago Farias]]></dc:creator>
            <pubDate>Mon, 07 Aug 2017 14:01:01 GMT</pubDate>
            <atom:updated>2017-08-12T03:31:54.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUviFQij6xRyPgkUNmOncQ.png" /></figure><p>If you’re familiar with an ORM, you’ve probably been bitten time and again by a very common problem when trying to query an object along with its relations. For instance, imagine a very simple relation between entities in a Ruby on Rails project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d00ce0f704f5efd4077d6d138bdfd11/href">https://medium.com/media/6d00ce0f704f5efd4077d6d138bdfd11/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc15da09774ffec4fb3ee53973fa5151/href">https://medium.com/media/dc15da09774ffec4fb3ee53973fa5151/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0a3f73d5a1b4bae4b92cace0114d0ca/href">https://medium.com/media/f0a3f73d5a1b4bae4b92cace0114d0ca/href</a></iframe><p>Now, what happens when we try to get the user for each book?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e36a821fdbc1c0b8a24d3f82a30a51b/href">https://medium.com/media/5e36a821fdbc1c0b8a24d3f82a30a51b/href</a></iframe><p>If you look at the Rails’ output, you’ll notice something is off as the output shows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea03b9aa37b79b30c2eb9e980fbe583c/href">https://medium.com/media/ea03b9aa37b79b30c2eb9e980fbe583c/href</a></iframe><h3><strong>“Something is rotten in the state of my queries”</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pZxMZW6eiCDuBwL9_cyPQg.png" /></figure><p>That, my friends, is the problem of N+1 queries itself. Our initial query (the 1 in N+1) returns a collection of size N, which, by its turn, runs a query for each one of them in the database (the N in N+1).</p><p>Well, luckily we only have 3 books in this example. But the performance hit can be very significant. Imagine what could happen if we had millions of them! Depending on how big a collection you have, your computer could even explode! Nope, not really… But your app surely could stop. And I think it would be worse than the former, since in the event of an explosion you can always blame the hardware. Notice, on the other hand, that the N queries are very fast (once they are processed in the database) since they’re matching on a specific id column (an index), therefore improving performance. But don’t be fooled: whenever you can trade N+1 for two or even one query, just pull the trigger. The cost of I/O (especially if the DB is not in the same machine as the app) communicating with the DB is the culprit here.</p><p>In this post we’ll examine 3 methods/strategies developed in ActiveRecord (as well) to circumvent the problem of N+1 queries: preload, eager_load and includes.</p><h3><strong>“There is special providence in #preload”</strong></h3><p>One way to solve this problem is by having 2 queries: the first one for fetching the association data and the second one would be the query with the final results. Something along the lines of:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b92c78482758d854320566eb63e2d038/href">https://medium.com/media/b92c78482758d854320566eb63e2d038/href</a></iframe><p>And the resulting queries output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e74a631bde05e7547854db6a80d7b050/href">https://medium.com/media/e74a631bde05e7547854db6a80d7b050/href</a></iframe><p>Aah! It is slower than the N+1 way! Not generally, no. In this specific example it was, yes. But that’s only because our seed data consisted of only 3 books. So while preload takes <strong>0.7ms</strong> to run 2 queries, N=3 takes (in my machine) just <strong>0.4ms</strong> to run. It’s ok, though. Just keep in mind these N+1 queries are using a Postgres index table (id as primary key) and therefore being blazingly fast. For the vast majority of cases 2 queries will beat N+1 all day long.</p><p>But there is always the flip side. Well, what do you think would happen if we tried to filter the query just a bit more? Something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47cf673b8d95dd6b75ccd55c33f5942f/href">https://medium.com/media/47cf673b8d95dd6b75ccd55c33f5942f/href</a></iframe><p>So ActiveRecord complained because it didn’t find a column “users.name” in the query. Of course, not. preload (the name is a hint) only loads or fetches the data from an association previously in a <strong>different </strong>query. To use “users.name” in the query, we would need to join the two tables. It’s clear now that preloadis not the definitive answer. For instance, what if I need to access an association within the query? Well, that takes us to the next strategy.</p><h3><strong>“A join, a join! My kingdom for a join!”</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVR9abA9EZVg2oHJwuKsbg.png" /></figure><p>The problem we had in the previous strategy was that we couldn’t access another table’s columns within the query. That happens because preload<strong>always</strong> uses separate queries. Fear not. eager_loadexists for a reason. It loads the data from an association with only one query using left joins to populate associated records. For instance, we could now do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f772af34a4d3bbb53ec9c804d06c10dc/href">https://medium.com/media/f772af34a4d3bbb53ec9c804d06c10dc/href</a></iframe><p>First of all, Rails’ log screams “LEFT OUTER JOIN” in your face. That’s very unpolite. But ActiveRecord is kind of a know-it-all, it’s just trying to show off on how much SQL it knows. Nevermind about that. But this is actually important to remember: eager_load will <strong>always </strong>use one query with a left outer join (don’t worry about the outer, it’s the same as a left join).</p><p>Secondly, notice that we can access fields from the associated table (users), since ActiveRecord loads both tables into memory (careful about that). That was exactly the problem we had with preload. Now we can run the following and it’s gonna work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56a17395dfa751f1426f1916fd4d94c1/href">https://medium.com/media/56a17395dfa751f1426f1916fd4d94c1/href</a></iframe><p>Another interesting thing here is that it’s different from joins . What’s the deal with joinsthen? A few:</p><p>1. joins uses an <strong>inner join</strong> instead of a <strong>left outer join</strong>.</p><p>2. different goal: should be used to filter results from a query, <strong>not loading records with its associations</strong>. It does <strong>NOT </strong>eagerly load associations, thus not preventing the N+1 queries.</p><p>3. it’s fine to use when you want to filter results from a query without accessing fields from the associated tables, because it does not load or populate associated tables into memory, it only uses them to filter results.</p><p>These 3 points also mean that we can use joinsalong with preload, eager_load and (as we’ll see) includes. That is precisely because they have different purposes in life.</p><p>Anyway, which one should I go for: eager_load generating only one query with left joins or preload fetching associated data in a separate previous query? You know what? ActiveRecord created this lovely mess for us (and I’m thankful for it ❤), so let’s see how it also solved or at least simplified this dilemma with includes.</p><h3><strong>“There is nothing either good or bad, but #includes makes it so”</strong></h3><p>So, what’s the use of includes, you may ask, given that we already mentioned the two eager loading strategies used by ActiveRecord? Prior to Rails 4, includeswas used to delegate the responsibility of the decision to which eager loading strategy to use in each case. Basically, it would spy on your <em>where</em> or <em>order</em> conditions to see if you referenced an associated table there and, if you did, it would delegate to eager_load (as obviously it would need to join tables). Otherwise it would just use preload. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b65c447e5b2eb5eaa517796c54c762a/href">https://medium.com/media/8b65c447e5b2eb5eaa517796c54c762a/href</a></iframe><p>Now, the default case (<em>where</em> condition does not mention associated table):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/959554c1d0e4efa453d06ef972572814/href">https://medium.com/media/959554c1d0e4efa453d06ef972572814/href</a></iframe><p>But since Rails 4, the Rails team has kind of given up on this. In the deprecation warning they mentioned that <em>“doing this without writing a full-blown SQL parser is inherently flawed. Since we don’t want to write an SQL parser, we are removing this functionality”</em>. Plain and simple, includes will work exactly like preloadfrom Rails 5 and above. The former example will even throw an error in Rails 5, as preloadwill tell you that it is not possible to access columns in an associated table that was not joined. There is one caveat, though. If you want includesto join the associated table(s), you need to explicitly tell it by using the referencesmethod. Basically it would become:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b6c4a89e21e799ffd3a2f0ebd7527a/href">https://medium.com/media/e6b6c4a89e21e799ffd3a2f0ebd7527a/href</a></iframe><p>In my opinion, prior to Rails 4 includeswas as cool as the other side of the pillow. I understand that it changed because of a very reasonable implementation obstacle, but the fact that referencesexists uniquely for telling it to use eager_load is not really DRY or even clear at all. references cannot be called without includesand includeswithout referencesalways uses preloading strategy! Why not simply call eager_loadinstead of the whole query.includes(:user).references(:user) piece? Why not simply call preload instead of includes(without its personal stalker), which is much more intent revealing? I’ve seen <a href="https://stackoverflow.com/questions/34637462/comparing-references-requirement-on-includes-vs-eager-load">some responses for this</a>, but I don’t know… just not convinced yet. Also, includes has an overhead on top of it to decide which strategy to delegate to. This overhead causes it to be a <a href="http://www.chrisrolle.com/en/blog/benchmark-preload-vs-eager_load">bit slower</a> than the other 2 methods. Anyway, these Rails folks are really smart. They will surely come up with something here.</p><blockquote>Why not simply call `eager_load` instead of the whole `query.includes(:user).references(:user)` piece? Why not simply call `preload` instead of `includes` (without its personal stalker), which is much more intent revealing?</blockquote><h3><strong>“Sweets to the sweet” — A summary</strong></h3><ul><li>preload, eager_loadand includesare birds of a feather: they are all <strong>eager loading</strong> strategies.</li><li>joins is different from the three amigos: Uses<strong> inner join</strong> to filter queries <strong>without</strong> loading relations.</li><li>preload: loads associated tables using always a <strong>separate quer</strong>y.</li><li>eager_load: loads associated tables using always a <strong>left join</strong>.</li><li>includes: previously (&lt; Rails 4) was smart (kinda) to find out which strategy was better: eager loading or preloading. Since Rails 4 it uses preloading unless explicitly told to use left joins with references.</li><li>references: cannot be used without includes, but the inverse can happen and will call preload.</li></ul><h3><strong>“There are more things in ActiveRecord, Horatio, than are dreamt of in your code”</strong></h3><p>“To be or not to be?” Prince Hamlet was facing a serious dilemma on whether he should murder his uncle, then step father, King Claudius, or not. Well, I don’t know about that. But as we’ve seen in this post, we shouldn’t be reluctant on killing N+1 queries. That is not really the question you should be asking yourself. The real question here is if you do or do not want to use joins in your queries, and to what extent. Just like in Hamlet, this is hardly a simple question. Hopefully, this post will help you elucidate some of your doubts about the use of ActiveRecord’s eager loading strategies, helping you to make sound decisions when it comes to querying objects’ associations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6728fcefea3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goiabada/to-join-or-not-to-join-an-act-of-includes-f6728fcefea3">To join or not to join? An act of #includes</a> was originally published in <a href="https://medium.com/goiabada">Goiabada</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>