Rails route constraints don't work as expected
I asked this question today about packing all routes in json format by default. I could have sworn it works before, but I might have been wrong.
How it works:
resources :insurances, only: [:index, :show], :defaults => { :format => 'json' }
but this is not the case:
constraints format: :json do
resources :insurances, only: [:index, :show]
end
Am I missing something basic about how constraints work?
source to share
Block constraints check the Request object, which sometimes returns values as strings. Using the following code will be the same as your example :defaults
- the validation rake routes
should show a parameter { :format => 'json' }
on each of your resource routes.
constraints format: 'json' do
resources :insurances, only: [:index, :show]
end
If you prefer to use a character instead of a string format, you can do it via a lambda:
constraints format: lambda {|request| request.format.symbol == :json }
resources :insurances, only: [:index, :show]
end
Source: http://guides.rubyonrails.org/routing.html#request-based-constraints
source to share
I came across this question while trying to solve exactly the same problem. I solved my problem. I think what you want is this:
//config/routes.rb
defaults format: :json do
//Your json routes here
end
As you can see from the above link, you can also mix it in the visibility block like this:
//config/routes.rb
scope '/api/v1/', defaults: { format: :json } do
//Your json & scoped routes here
end
This is the version I was using.
Both approaches have been tried and they both work.
Test environment:
- Rails 5.2.2.1
- Ruby 2.6.0p0
source to share