Rails: Routing to a different controller based on request format

Posted by Jimmy Cuadra on Stack Overflow See other posts from Stack Overflow or by Jimmy Cuadra
Published on 2012-12-06T23:01:21Z Indexed on 2012/12/06 23:03 UTC
Read the original article Hit count: 231

Filed under:
|

I'm writing an app where I want all requests for HTML to be handled by the same controller action. I have some other routes that are JSON-specific. Here's what my routes look like:

Blog::Application.routes.draw do
  constraints format: :json do
    resources :posts
  end

  match "(*path)" => "web#index"
end

The problem is that constraints is being interpreted as "this route only works with the specified format" rather than "skip this route and try the next one if the request is not in the specified format."

In other words, navigating to /posts in the browser gives me a 406 Not Acceptable because the URL is constrained to the JSON format. Instead, I want it to fall through to web#index if the request is for HTML, and hit the resourceful route if the request is for JSON. How can this be achieved?

(Using Rails 3.2.9.)

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about url-routing