Restricting Action Formats Using Rails Routing Constraints

Posted by Weston Ganger on November 07, 2015

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"

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

Related External Links:

Posted in Rails and Tagged with routing rails 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts