Rails render & respond_to Method

TODO: move respond_to to another blog.

ActionController

The essence of ActionController::render is “generating response”.

There are three ways:

  • Call render to create a full response anew.
  • Call redirect_to to send an 402 HTTP status code to the browser.
  • Call head to create a header-only HTTP response.

If no response is set explicityly, then the view template with name corresponding to the action will be rendered. It means whenever you leave the action and no response is set, this mechanism will kick-in. E.g. when you early return from the action.

A Small Caveat of POST Action

For actions that modifies data (like POST method), use redirect seems be to a best practice implemented by the framwork. This is something called PRG (post/redirect/get) pattern. It’s anti-pattern to “render response”, since browser will discard it.

What

Both ActionView and ActionController has render method.

It’s confusing the documentation mix those two methods together.

How

The controller is able to render explicitly or implicitly.

  • Implicit: 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 path and render it.

  • Explicit:

  • render to render whatever stuff in named format. The content may be current action’s template, some other action’s template in or not in the same controller, a file, a raw string, etc.

  • respond_to to describe what to return for different requested formats.

Where

When

respond_to might play a supplemental role for render. As the doc states: render renders a template and assigns the result to self.response_body. And since the very beginning, only two formats are supported natively: html & json. While respoind_to act as a DSL, allowing us to describe what to respond for different formats requested. The doc for respond_to constantly mentions web-service, which it means certain rack-compliant web server that brings requested format information to our rails controller. So within respond_to, we can define what to return with the format object.

references: What’s the difference between using render instead of respond_with/to in a Rails API? - Stack Overflow

Who

It’s very interesting to read ActionController::Base and ActionView::Base. Those two Base classes play vital roles in dealing with web request.

Written on March 12, 2024