<?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 Nikki Holland-Plum on Medium]]></title>
        <description><![CDATA[Stories by Nikki Holland-Plum on Medium]]></description>
        <link>https://medium.com/@mnhollandplum?source=rss-428e886cbbdd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TaeWAFknxaGzu6d9</url>
            <title>Stories by Nikki Holland-Plum on Medium</title>
            <link>https://medium.com/@mnhollandplum?source=rss-428e886cbbdd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 14:11:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mnhollandplum/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 Add Slugs to an Existing Codebase]]></title>
            <link>https://medium.com/@mnhollandplum/how-to-add-slugs-to-an-existing-codebase-f9528e302285?source=rss-428e886cbbdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9528e302285</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Nikki Holland-Plum]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 03:11:37 GMT</pubDate>
            <atom:updated>2018-11-08T00:23:53.005Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Brief Overview of Slugs:</h3><p>Slugs are custom, sometimes descriptive URLs. In a basic Rails application, a show page is represented by the id of that instance of the resource by default. In order to use slugs, we need to override the param, generate the slug and include the new slug param in our routes. If we have already written our code and forgotten to include slugs, we have a little clean up to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*V2RXAYBVitasZ_FS0USMrA.gif" /></figure><h3><strong>Adding Slugs to an Existing Application:</strong></h3><p>So, you find yourself wanting to add slugs to your URLs after you’ve already written your Rails application, or you’re working with someone else’s codebase. I want to preface this writing with; you should always write in slugs at the beginning of your application if you can help it! But here we are, so let’s get started.</p><p>First, we need to create a migration to add slugs to our User resource. We want each user to have their own slug associated with them.</p><p>Let’s the migration command into our command line:</p><pre>rails g migration AddSlugtoUser slug:string:uniq:index</pre><p><strong><em>This will create a db/migrate/{date}_add_slug_to_user.rb</em> </strong>file. The inside of this file should look like this:</p><pre>class AddSlugToUser &lt; ActiveRecord::Migration[5.1]<br>  def change<br>    add_column :users, :slug, :string<br>    add_index :users, :slug, unique: true<br>  end<br>end</pre><p>(if not, let’s make those changes).</p><p>When everything looks right, run the migration through your command line.</p><pre>rake db:migrate</pre><p>Our <strong><em>db/schema.rb </em></strong>file should have updated and added <em>slug</em> to your User table as a string and an index.</p><pre>t.string &quot;slug&quot;<br>t.index [&quot;slug&quot;], name: &quot;index_users_on_slug&quot;, unique: true</pre><p>Let’s write some methods! Just kidding, we always, always, always (sometimes) write tests first. The first method we are going to write will be a model method, for this example, we’ll be using a User resource. We’ll need to locate our <strong><em>spec/model/user_spec.rb </em></strong>file<strong><em> </em></strong>and add this test.</p><pre>it “.generate_slug” do<br>  user = create(:user, name: “Ralph the Slug”)<br>  expect(user.slug).to eq(“ralphtheslug”)<br>end</pre><p>As longs as all of our tests were passing before, this shouldn’t cause any problems.</p><p>NOW, we can write our methods. Let’s locate our <strong><em>app/model/user.rb </em></strong>file. These methods will go at the very bottom of this file.</p><pre>def to_param<br>    slug<br>  end</pre><pre>private</pre><pre>  def generate_slug<br>    self.slug = name.downcase.delete(&quot; &quot;) if name<br>  end</pre><p>The first method, <strong><em>to_param</em></strong>, allows us to override the default param that rails uses to find an object (which is normally the id of that user).</p><p>Below that we have the <strong><em>generate_slug </em></strong>method, within the <strong><em>private</em></strong> method*. This method will assign a variable to the User object. We are taking the name of the User, making sure all of the characters are down-cased and taking out the spaces, so <em>Ralph the Slug </em>becomes <em>ralphtheslug</em>. The <em>if name</em> protects us from nils.</p><p>*A private method keeps all methods underneath only accessible by the class that it is created in.</p><p>There’s one last thing we need to add before we leave this file. If we would like to make sure all users are created with a slug attribute, we need to add a callback method at the top of the file.</p><pre>before_save :generate_slug</pre><p>Now let’s check our tests, did a bunch of stuff break? That’s okay, it’s all a part of the process.</p><p>Next, we need to fix up our routes. Our methods have changed how we find a user, but our routes are still looking for the id. In the <strong><em>config/routes.rb </em></strong>file we need to add our new param.</p><pre>resources :users, param: :slug</pre><p>(if you are limiting your resources, just tack the , param: :slug to the end.)</p><p>Next we need to checkout our controller file, <strong><em>app/controllers/users_controller.rb</em></strong>. In the <strong><em>def_show </em></strong>method, our @user instance variable is currently looking for the user based on the id param, but now that’s changed to our slug param.</p><p>Let’s change:</p><pre><a href="http://twitter.com/order">@u</a>ser = User.find(params[:id])</pre><p>to:</p><pre><a href="http://twitter.com/user">@user</a> = User.find_by(slug: params[:slug])</pre><p>If all of your tests are passing, congrats, you’re done. If not, you’ve only got one more step!</p><p>And FINALLY, we can clean up our tests! Basically, anywhere we were trying visit or assert the user_path(@user.id), we just need to get rid of the .id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*6gJMpq5hXI2wpBAmDSAiug.gif" /></figure><pre>user_path(@user)</pre><p>Yay! You have working slugs in your rails application!</p><h3><strong>Additional Thoughts:</strong></h3><p><strong>Unique slugs:</strong> One thing you may run into is violating the uniqueness validation. Each slug needs to be unique, but sometimes you’ll have issues with a user or other resources having the same name attribute. There are a few ways to avoid this. The first would be to use an attribute that is already validated as unique, like a <strong>username</strong>.</p><p>Another option is to add random numbers to the end of the slug. To do this update your <strong><em>generate_slug </em></strong>method in your user model.</p><pre>def generate_slug<br>    self.slug = name.downcase.delete(&quot; &quot;) + rand(10_000..99_999) if name<br>end</pre><p>Or use SecureRandom.uuid. This is a great option if you want to obfuscate, or protect a slug. The most common example of this would be for a transaction or receipt show page, that you wouldn’t want anyone to be able to guess.</p><pre>def generate_slug<br>    self.slug = name.downcase.delete(&quot; &quot;) + SecureRandom.uuid if name<br>  end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9528e302285" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>