Restricting Action Formats Using Rails Routing Constraints

Posted By Weston Ganger

I got super sick of getting the error that some web scraping bot is trying to access a format I don't support.

The constraints must be placed in the routes not in the controller. Here's how to restrict the formats to whatever you specify.

# config/routes.rb

# One Format
resources :posts, constraints: {format: :html}

# Multiple Formats
resources :posts, constraints: {format: /(html|json|js)/}

# Multiple resources and routes
scope constraints: {format: /(html|json|js)/} do
  resources :posts
  resources :comments
  get "/profile", to: "users#profile"
end

Just like that the format is restricted to your choice of formats.

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:November 07, 2015