A truly default route

A truly default route
What would routes.rb look like if I want EVERYTHING to go to a controller action called, hmm, ‘everything’ in static_pages.rb?

Ralph Shnelvar

Here's the bottom of one of my routes.rb files:

  # this has to be the last option in order to work with unprefixed routes
  get '/:slug', to: 'pages#show', constraints: lambda { |request| Page.pages.include? request.path_parameters[:slug] }
  
  get "*any", via: :all, to: "errors#not_found"

That's not exactly what you asked for, but it's fairly close.

Walter

Re: [Rails] A truly default route
Walter,
This is WAAAY above my head.
Would you please give an explanation? Are both lines necessary?
Ralph
Thursday, February 22, 2018, 7:05:30 PM, you wrote:
__WLD> Here’s the bottom of one of my routes.rb files:

Sure.

This is from a CMS where pages can be accessed by their "slug" parameter. So a link to www.example.com/some-unique-name will resolve to PagesController#show with the :slug parameter populated with the value 'some-uniqe-name'.

I also added the constraints bit (optional if you really just mean for all requests to be mapped to the one controller/action pair) so that only slugs that were real (as opposed to typos or whatever) would be routed to the PagesController. In the Page model, there is a method called pages:

  def self.pages
    @pages = Page.pluck(:slug)
  end

That just gives me the complete list of possible real slugs, so I can ignore anything else. And in the PagesController, I have the set_page method to allow pages to be found by their slug or their id:

  def set_page
    if params[:slug]
      @page = Page.find_by(slug: params[:slug])
    else
      @page = Page.find(params[:id])
    end
  end

That runs in a before_action callback, so my show method is empty.

The last line in the routes is a catch-all that sends a 404. It is only reached if none of the other routes matched, so it only fires when I get a request that I don't legitimately handle. I was getting a LOT of Wordpress "fuzzing" attacks on this server, and I didn't like them clogging my logs.

Walter