Rails

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"
end

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


Related External Links:


Posted in Rails and Tagged with routing rails 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts