O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.5. Rendering

An action's main goal is to enable the formulation of a response for each user request. To be exact, that's one response per request. An action typically sets up one or more instance variables and renders a template that uses these variables to present them in a meaningful way. This is not always the case though; when appropriate, a request can send only headers back and not the actual body of the content. This is fairly common for some Ajax requests.

NOTE

Because only one response is sent back to the client, at most an action should invoke the rendering of one template.

Whether a template is involved or you're sending a string of text or just headers back to the template, the method of choice is the fittingly named render.

8.5.1. render

Invoked without parameters, render will render the default template for the given action. For example, the following snippet renders the hello.html.erb template back to the client:

def hello
    render
end

Notice that this is the default behavior, and the explicit render is not required. As mentioned in the previous section, for such a basic case, not even the action needs to be declared because Rails automatically looks for the template.

If you are working with a legacy Rails application, the template that is rendered could be called hello.rhtml. This is the old-fashioned extension for HTML ERb templates in Rails.

By passing a :text argument, you can render a string back to the browser thus bypassing any template rendering:

def ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required