Read more

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

Arne Hartherz
May 20, 2014Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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 Show archive.org snapshot ; 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.

Posted by Arne Hartherz to makandra dev (2014-05-20 10:52)