JT Book a call

Blog

A Simpler Way to Set Content Types in Rails

Published

2 min read

In this post

Rails now lets you set content types with less code. This new feature makes your work easier.

The Change #

You can now use a short symbol instead of a long text string. Here’s what it looks like:

Old way:

response.content_type = "text/html"

New way:

response.content_type = :html

Benefits #

This change helps in three ways. First, your code becomes shorter. Second, it matches how Rails handles other formats. Third, you don’t need to remember the full content type text.

Using the Feature #

To try this, update to Rails 8.1. The change was merged in November 2024 (rails/rails#53236) and first shipped in Rails 8.1.0, where it is listed in the Action Pack changelog. Then start using symbols for your content types.

What the symbol turns into #

Rails looks the symbol up in its list of registered MIME types and writes the full header for you, charset included. On Rails 8.1:

response.content_type = :html
response.content_type # => "text/html; charset=utf-8"

response.content_type = :json
response.content_type # => "application/json; charset=utf-8"

A typo fails loudly, which is what you want:

response.content_type = :nope
# => ArgumentError: Unknown MIME type nope

Strings still work as before, so "text/csv" gives you "text/csv; charset=utf-8". You can mix both styles in one app while you migrate.

What Rails 8.0 and earlier do with a symbol #

On Rails 8.0 and earlier, the symbol is accepted without any error, but it is turned into a plain string. The same line on Action Pack 8.0.5.1 gives:

response.content_type = :html
response.content_type # => "html; charset=utf-8"

html isn’t a valid content type, so browsers and API clients get a header they can’t use, and Rails doesn’t warn you. If your app is still on 8.0, keep the strings until the upgrade.

Credit #

Petrik de Heus built this feature. His work helps make Rails better for everyone.

Read next

Tell us what you need built

JetThoughts has been building software since 2008. Book a call, or write to sales@jetthoughts.com. You'll leave the call with a written one-page scope within 2 working days.

#01 Paul Keen
Paul KeenFounder & Open Source Contributor

A 30-minute call; pick a time.