forthowin
forthowin

Reputation: 387

Why is my catch-all route not working for some routes?

I have this in routes.rb:

resources :emergencies, except: [:new, :edit, :destroy], defaults: { format: :json }
match '*path', to: 'application#page_not_found', via: :all

I also have this in application.rb:

config.exceptions_app = self.routes

And my application_controller.rb looks like this:

class ApplicationController < ActionController::Base
  def page_not_found
    render json: { message: 'page not found' }, status: :not_found
  end
end

I have a set of test suites that tests the :new, :edit, and :destroy route. The routes for :edit and :destroy pass, returning the message page not found as expected, but the :new route returns null. Infact, anything like /emergencies/anything would render null, but something like /emergences/new/new would work correctly. Any idea on why this is happening and how I can fix it so that the route /emergencies/new is hitting the page_not_found action?

Upvotes: 1

Views: 883

Answers (2)

Elvn
Elvn

Reputation: 3057

I see this already has an answer above, but there's a very straightforward catch all 301 redirect implementation when a route is not found. In the example below page not found redirects to root.

Rails.application.routes.draw do
  root 'static_pages#home'
.
.
. 

  # This is a catchall 301 redirect to home (does not help with (e) type errors --  MUST BE LAST )
  get "*path", to: redirect('/')
end

Upvotes: 0

Brad Werth
Brad Werth

Reputation: 17647

Run rake routes to see how your routes lay out.

You will notice that the show route matches emergencies/:id (this includes emergencies/new, for example).

Routes match from the top down. Normally, resources declare the new route before the show route, to catch what would match the future declarations.

If you can, add a constraint to your show route, if not to match the id, at least to not match the new. or you could keep the resource routes and kick them to your page_not_found method in a before_filter in the controller...

Upvotes: 1

Related Questions