4

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?

Community
  • 1
  • 1
user2954587
  • 4,661
  • 6
  • 43
  • 101

2 Answers2

7

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:

  • Rails 5.2.2.1
  • Ruby 2.6.0p0
JBlanco
  • 517
  • 5
  • 9
2

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

Alex
  • 1,434
  • 10
  • 17