<?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 Eliot Swank on Medium]]></title>
        <description><![CDATA[Stories by Eliot Swank on Medium]]></description>
        <link>https://medium.com/@eliotswankdev?source=rss-882e647ceae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QfrDUad_wTlq8ilV</url>
            <title>Stories by Eliot Swank on Medium</title>
            <link>https://medium.com/@eliotswankdev?source=rss-882e647ceae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:52:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eliotswankdev/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[How to Set Up a Many-to-Many Relationship in Rails: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@eliotswankdev/how-to-set-up-a-many-to-many-relationship-in-rails-a-step-by-step-guide-b34570818122?source=rss-882e647ceae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b34570818122</guid>
            <category><![CDATA[shoulda-matchers]]></category>
            <category><![CDATA[many-to-many]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[activerecord]]></category>
            <dc:creator><![CDATA[Eliot Swank]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 21:13:46 GMT</pubDate>
            <atom:updated>2019-03-24T19:30:34.014Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the things with which I struggled when learning Ruby on Rails was setting up the many-to-many relationship models. While the web has a massive amount of pages that mention this topic, I found that there was no clean, clear, concise step-by-step instruction to do this. So, I’ve decided to share the process that I use.</p><p>This guide presumes that you’ve created your app using the rails new command, and you know what features you want to implement, and you have written a test (or tests) for those user stories.</p><p>I love the shoulda-matchers gem for rspec for easy in-line validations of the model relationships, so for this tutorial to work for you, you’ll need to put gem &#39;shoulda-matchers&#39; in your gem file, and the following block of code in your rails_helper.rb file, otherwise the validation test syntax in this article won’t work.</p><pre>Shoulda::Matchers.configure do |config|</pre><pre>  config.integrate do |with|</pre><pre>    with.test_framework :rspec</pre><pre>    with.library :rails</pre><pre>  end<br>end</pre><p>The example we’ll be working though here is a rarity in modern times — a bookstore: A bookstore has many books, and books can be at many libraries (as in multiple copies of the same book at different bookstores).</p><p>The first step here is to generate the models, since : book and bookstore . Let’s say for purposes, books have a title and author, and a bookstore has a name and location, all strings.</p><p>Rails does the hard work for you, and you can use a generator to make the models. It will also create empty test files for us that we’ll fill out in a bit.</p><p>From the command line, run rails g model book title:string author:string .</p><p>This command will create a book model with a title and author that will be strings in our database.</p><p>Then migrate your database: rake db:migrate</p><p>Next, create the bookstore model: rails g model bookstore name:string location:string</p><p>And again rake db:migrate</p><p>Now, it’s time for the join table. We need to create a model that references both the book and the bookstore models. Here’s how we do that:</p><p>rails g model bookstore_books book:references bookstore:references</p><p>This command will create the model/join-table with the relationship syntax built-in, so that’s super handy.</p><p>Run rake db:migrate once more.</p><p>Now, we need to write some model tests for validating the relationships. If you have your test environment setup, the rails model generator should include an empty test file that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmnVO02AcRl0eXl1HAmwbg.png" /><figcaption>Example of the empty test generated with the model</figcaption></figure><p>On line 4, we need add some relationship validations:</p><p>it { should have_many(:bookstore_books)}</p><p>it {should have_many(:books).through(:bookstore_books)}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*dDLapdCAufBZ5KLtOHxQ9w.png" /><figcaption>Relationship tests for a many-to-many relationship</figcaption></figure><p>Do the same thing in bookstore_spec.rb (but, obviously change books to bookstores in the test.</p><p>Then, in your join model test, bookstore_book_spec.rb , add the following:</p><p>it { should belong_to(:book)}</p><p>it {should belong_to(:bookstore)}</p><p>Run the tests, and they fail. Big time. That’s ok, though, because *RED, GREEN, REFACTOR*.</p><p>We can easily make them pass by adding the has_many helper in our book.rb and bookstore.rb models, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*-HPXh0fNjzNaMFUol0NgeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*5hTtZapX0YblrO8nF9VFyg.png" /></figure><p>The big thing to note here is that the join table comes first and then the table *through* the join table next. If you don’t have these in the correct order, the relationship will not work.</p><p>And that’s it! You will be able to create a book object that’s tied to a bookstore by using bookstore.books.create(params) and you’ll be able to reference these objects in a similar fashion: bookstore.books.where(publish_year: 2018) will get you all the books published in 2018 for that particular bookstore.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b34570818122" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>