Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book