Global request-based constraints in Rails

Whilst the concept of constraints is well-documented in the official Rails guides, the docs only seem to cover how you implement a constraint on a per-route basis.

But, I want the same constraint for my entire application i.e. a global constraint. This is not clearly documented in the Rails guides and is not the most obvious thing to implement (especially as it’s not something you actually write that often).

In my rails-api application, I only want to respond to JSON requests. To configure a global constraint I did this:

Rails.application.routes.draw do

  scope :constraints => { format: :json } do
    # your routes here


Hopefully you find this useful.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s