Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes constraints not working as expected

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?

like image 683
user2954587 Avatar asked Feb 10 '23 13:02

user2954587


2 Answers

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
like image 108
JBlanco Avatar answered Feb 16 '23 05:02

JBlanco


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

like image 32
Alex Avatar answered Feb 16 '23 07:02

Alex