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
> To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/1366615011.20180222195308%40dos32.com.