Note that there are some explanatory texts on larger screens.

plurals
  1. PORails routing: format constraints when none is specified
    primarykey
    data
    text
    <p>For Reasons™, I want to have one controller handle html requests and another handle json api requests.</p> <p>I've got this in my routes:</p> <pre><code>scope module: :api, as: :api do constraints format: :json do resources :users end end constraints format: :html do resources :users end </code></pre> <p>This works great when the url sports a suffix: <code>/users.json</code> goes through my <code>Api::UsersController</code> à la <code>api_users_path</code>; <code>/users.html</code> goes through my <code>UsersController</code> à la <code>users_path</code>.</p> <p>However this does not behave as expected when there is no suffix in the url. Implementing the constraints as lambda show things go wrong:</p> <pre><code>#=&gt; visiting /users scope module: :api, as: :api do constraints -&gt;(request){ puts "In api: #{request.format}"; request.format == :json } do resources :users end end constraints -&gt;(request){ puts "In html: #{request.format}"; request.format == :html } do resources :users end #=&gt; In api: text/html #=&gt; (request.format == :json) =&gt; false </code></pre> <p>and yet it ends up in the api controller.</p> <p>No fiddling with custom constraint classes or lambdas or anything prevents rails from selecting the first route defined if none of the constraints match.</p> <p>I can't find a way to write a constraint that catches when the url lacks a suffix, and I don't feel as if I should have to–<code>request.format == :html</code> reports true when I'm navigating to <code>/users</code>. Why isn't the second constraint catching that?</p> <p>Also, while I could "fix" this by changing the order of these two, I'd much rather know why my constraints aren't working right.</p> <p>Does anyone know how to enforce these constraints differently to effectively switch on whatever the format is, not just the url suffix, or have an explicit constraint that accommodates no format suffix?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload