Restrict route to terminate with trailing slash

I have two wildcard routes that look like this:

get '*country_path/', to: 'country#list', constraints: { country_path: /\/$/ }
get '*country_path/:title', to: 'country#show'

The list of countries # should be called when the url has a trailing slash. Examples:

www.example.com/usa/california/
www.example.com/usa/california/abc/

show # # should be called when it does not have a trailing slash. Examples:

www.example.com/usa/californa/travel
www.example.com/usa/californa/average-income

Currently my restriction does not work, since all requests go to the list of countries.

What is wrong with my route restriction?

+4
source share
2 answers

You should ask yourself if this is really the best way to accomplish what you are trying to do. Websites don't care about the final slashes in directories at all. For instance:

www.facebook.com/username

It will open you in the same place as:

www.facebook.com/username/

- , , , -. , , SEO, . , , . , .

: list show, URL. :

www.example.com/usa/california/list
www.example.com/usa/california/abc/list

country#list, "california" "abc". :

www.example.com/usa/californa/travel/show
www.example.com/usa/californa/average-income/show

country#show. . . . Rails Routing from Outside In.

+7

, Rails / , , . - . , :

# config/routes.rb
class TrailingSlashMatcher
  def matches?(request)
    uri = request.env["REQUEST_URI"]
    uri.present? && uri.end_with?("/")
  end
end

Rails.application.routes.draw do
  get '*country_path', to: 'country#list', :constraints => TrailingSlashMatcher.new
  get '*country_path/:title', to: 'country#show'
end

( ).

, . , .. , REQUEST_URI env , . env["PATH_INFO"] , / , .

, , . / . (, / ..). (, ).

+1
source

Source: https://habr.com/ru/post/1546902/


All Articles