Today I Learned

hashrocket A Hashrocket project

Add a Default Format to Routes in Rails

When routing in Rails

# config/routes.rb

resources :users

sure you can respond to say json by going to the format directly (/users.json). What if you want that to always be the format without requesting it in the url? Normally by default we would get HTML if we declare nothing.

Turns out you can pass a defaults option to your routes with format being one of the things that can be accepted.

# config/routes.rb

resources :users, defaults: {format: :json}

Now requesting /users will render the json response as well as /users.json.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.