How to configure WordPress-like permalinks?

I want to be able to have post permalinks appear in the root of the site. So, for example, a post with a permalink “hello-world” should appear as “mysite.com/hello-world”, instead of “mysite.com/posts_controller/hello-world.”

How would I go about doing something like this?

Related posts

Leave a Reply

2 comments

  1. I believe that you already have a “slug” field in your posts model.
    If your post controller has that into account, you just need to add the correct route for instance:

    match '/:slug' => "Posts#show"
    

    Otherwise, if don’t have the slug in your model, you can use the Stringex plugin. It’s an easy way to automatic create slugs for your posts.

    class Post < ActiveRecord::Base
      acts_as_url :title
    end
    

    It will create the slug from your title and save it to the slug column.

    In the controller you can find the correct post like this:

    def show
      @post = Post.find_by_slug(params[:slug])
    end
    
  2. In your routes:

    match '/:slug' => "Posts#show"
    

    Then in your controller you could do something like:

    Post.find_by_slug(params[:slug])
    

    Note: you will need to generate this slug value and store it in the Post model.

    Also have a look at friendly_id for a tried and tested way of doing this (if you need something more complex).