How to Explicitly Render a Different View in Rails

2 min read

A standard Rails controller receives an incoming HTTP request, generates the data needed for the response, and renders an HTML view template.

An API controller returns JSON or XML response data, but that's a topic for a separate blog post.

By convention, the Rails view templates are stored under the app/views directory, in the folders named after the controllers. The name of the folder is the snake_cased version of the controller name, after stripping the string Controller from it. There's a view file named after each action.

For example, the views for the PostsController controller are stored under the app/views/posts directory. If this controller has two actions named show and index, there will be two view templates:

  1. app/views/posts/show.html.erb
  2. app/views/posts/index.html.erb

Rails automatically figures out which view template to render based on the action name. That is, if you do not explicitly render something at the end of a controller action, Rails will automatically look for the action_name.html.erb template in the controller's view directory and render it.

In those rare cases where you want to render a different view, you can use the render helper method as follows:

class PostsController < ApplicationController
  def index
    @posts = Post.all
    render "articles/index"

In this example, Rails will render the app/views/articles/index.html.erb view template, instead of the app/views/posts/index.html.erb template.

Did you know? You can customize the behavior of render in various ways. You can render the default view for a Rails template, or a specific template (like we just did), or a file, or inline code, or nothing at all. You can also render text, JSON, or XML. Finally, you can specify the content type or HTTP status of the rendered response as well. We'll learn about them all in future posts in this series, so stay tuned.

That's a wrap. I hope you found this article helpful and you learned something new.

As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.

If you'd like to receive future articles directly in your email, please subscribe to my blog. Your email is respected, never shared, rented, sold or spammed. If you're already a subscriber, thank you.