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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)