Posted about 8 years ago. Visible to the public. Deprecated.

When using "render :text", set a content type

This card is very old. Modern Rails no longer supports render :text.

When your Rails controller action responds with only a simple text, render text: 'Hello' may not be what you want. You should not even use it on Rails 4.1+ any more.

By default, a "text" response from a Rails controller will still be a sent as text/html:

render text: 'Hello' response.body # => "Hello" response.content_type # => "text/html"

While this may not be too relevant for a Browser client, the response's content type is simply wrong if you want to send a plain-text response, and can cause trouble. \
For example, consider a middleware that transforms HTML responses Archive ; it would also touch such wannabe-plain-text responses sent with the incorrect content type.

To avoid that, simply set your content type properly:

render text: 'Hello', content_type: 'text/plain' response.body # => "Hello" response.content_type # => "text/plain"

Latest Rails

Rails 4.1 deprecates render :text. You should use render :html or render :plain instead.

render html: 'Hello' response.body # => "Hello" response.content_type # => "text/html"
render plain: 'Hello' response.body # => "Hello" response.content_type # => "text/plain"

There is also render :body which does not set a content type, so it is probably not really what you want in such cases.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Arne Hartherz
Last edit:
7 months ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more