Implementing Redirects in Rails
In this guide we will walk through implementing redirects in a Ruby on Rails application through the controller.
Guide Tasks
  • Read Tutorial

In the previous lesson we found that we have a little bit of a routing bug: when users navigate to a Topic url such as:

http://localhost:3000/topics/my-title-99/posts

The page loads find, however if we remove the call to /posts we get an error. This isn't ideal since most users are uses to being able to go to links such as:

We already have our Topic page built, so all we need to do is implement a redirect so that when users go to a URL such as http://localhost:3000/topics/my-title-99 it will automatically redirect them to the posts index page. We might have been too hasty when we pulled that out originally, let's remove the except argument for our topic routes.

Opening up the routes.rb file, make the following change:

# config/routes.rb

  resources :topics do
    scope module: :topics do
      resources :posts, except: [:new, :create]
    end
  end

And now in the TopicsController we can add in a show action, however this time we won't use the old view, we'll redirect the user to the posts index action.

  def show
    redirect_to topic_posts_path(topic_id: @topic)
  end

Make sure that the before_action method in the controller that calls the set_topic method is still including show in its list of arguments, I didn't remove that when we removed the orphaned view a few lessons ago.

If you start the server up you'll see that our broken page is now working properly and redirecting.

So what exactly is going on here? When the Rails router gets the RESTful route call from the browser it looks in the controller and the associated controller action to see what view should be rendered. By default the controller looks for the view that matches the action:

  • show action points to the show.html.erb view
  • index action points to the index.html.erb view

This is part of the Rails magic and how Rails controllers automatically look for corresponding view template files. However we have full control over what templates we want to render and we can also perform redirects like we did above.

Now that we've fixed that error we can move onto fixing the fonts so they match the mocks, and we'll do that in the next guide.

Coding Resources