[RAILS] Avoid matching * path at the end of routes.rb when accessing the URL of the [ActiveStorage] file

If there are routes such as * path at the end of config / routes.rb, It matches before the endpoint (/ rails / active_storage / ...) [^ 2] that indicates the ActiveStorage file.

[^ 2]: Click here for definition https://github.com/rails/rails/blob/v5.2.4.4/activestorage/config/routes.rb#L4

config/routes.rb


Rails.application.routes.draw do
  ...

  get "*path" , to: redirect('/')
end

To avoid this, do as follows.

config/routes.rb


Rails.application.routes.draw do
  ...

  get '*path' , to: redirect('/'), constraints: lambda { |req|
    req.path.exclude? 'rails/active_storage'
  }
end

Now you can set the paths containing rails / active_storage to not match.

About the constraints option

Interpretation as an option to impose constraints on specific routes. Use as follows.

# match `/users/A12345`, but not `/users/893`
get 'users/:id', to: 'users#show', constraints: { id: /[A-Z]\d{5}/ }

# match port 3000 only
get :users, to: 'users#index', constraints: { port: '3000' }

You can also specify lambda as described above. [^ 1]

get "hi", to: redirect("/foo"), constraints: ->(req) { true }

[^ 1]: Strictly speaking, you should specify an object that can be called by the call method that takes request as an argument. It seems that the target routing matches only when call called for each request returns true. Although not mentioned in this post, matches? Is also acceptable. (Test code, [Implementation part](https://github.com/ rails / rails / blob / e44b3419d44b5fa6e66305fe703f34bb63932593 / actionpack / lib / action_dispatch / routing / mapper.rb # L41-L42)

reference

Recommended Posts

Avoid matching * path at the end of routes.rb when accessing the URL of the [ActiveStorage] file
Why put a line break at the end of the file