I asked this question earlier today about wrapping all routes into default json format. I could have sworn it was working earlier but I may have been mistaken.
How come this works:
resources :insurances, only: [:index, :show], :defaults => { :format => 'json' }
but this does not:
constraints format: :json do
resources :insurances, only: [:index, :show]
end
Am I missing something basic on how constraints work?
I stumbled upon this question trying to solve the exact same problem. I have solved my problem. I think what you want is this:
//config/routes.rb
defaults format: :json do
//Your json routes here
end
I found the solution here
As you can see in the link above you can mix it within a scope block as well like this:
//config/routes.rb
scope '/api/v1/', defaults: { format: :json } do
//Your json & scoped routes here
end
This is the version I used.
Tested both approaches and they both work.
Test Environment:
Constraints in block format check against the Request object, which sometimes returns values as strings. Using the following code will do the same as your :defaults
example - checking rake routes
should show a { :format => 'json' }
option on each of your resource routes.
constraints format: 'json' do
resources :insurances, only: [:index, :show]
end
If you'd prefer to use a symbol instead of the string format, you can do so 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With