Skip to main content

Friendly URL with Categories and Category Posts for Rails!

By February 5, 2014Rails, Ruby

So one of the items I was working on today was dealing with SEO friendly URL’s and because of the way Rails work, you always end up with the controller name in the URL as well. This can sometimes work, but not everyone wants it!

The other issue that I had to also consider was that my posts weren’t using the ID’s like most sites use – it used a slug from the FriendlyId gem. The structure of the site was quite simple; you have your categories and each of the categories had many posts. So now I needed a way to have the posts listed in a pretty way.

After a bit of research, it turned out to be a simple two part fix.

The Code

config/routes.rb

  resources :categories, :path => '/' do
    resources :posts, :path => '/'
  end

  resources :categories, :posts

app/views/categories/show.html.erb

    <%= link_to post.title, category_post_path(post.category.slug, post.slug) %>

The Breakdown

The :path key replaces your controller name with whatever you set it to. If I had used :path => ‘/foo’, my controller name in the URL would be replaced with foo instead.

Because each category had many posts, in order to have the category show up in the URL as well, I needed show that posts were related to the categories hence line 1-3. And because I have replaced the :path with just a forward slash, I have removed the “posts” controller name.

Now because I was using FriendlyId, I had to change the link a little as you can see above in the second set of code. Don’t forget that you’ll need to run Rake Routes to get the new path based on the category-post combination. When all is done, you’ll have a URL as such:

http://example.com/category_slug/post_slug