LoginSignup
2
0

More than 3 years have passed since last update.

[ActiveStorage] ファイルのURLにアクセスしたときに routes.rb 末尾の *path にマッチしてしまうのを避ける

Posted at

config/routes.rb の末尾に *path などのルーティングがあると、
ActiveStorageのファイルを示すエンドポイント(/rails/active_storage/...)1よりも先にマッチしてしまう。

config/routes.rb
Rails.application.routes.draw do
  ...

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

これを回避するためには以下のようにする。

config/routes.rb
Rails.application.routes.draw do
  ...

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

これで rails/active_storage を含むパスがマッチしないように設定できる。

constraints オプションについて

特定のルーティングに制約(constraints)を与えるためのオプションという解釈。
以下のようにして使う。

# 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' }

上述のようにlambdaを指定することもできる。2

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

参考


  1. 定義はこちら https://github.com/rails/rails/blob/v5.2.4.4/activestorage/config/routes.rb#L4 

  2. 厳密には request を引数に取る call メソッドが呼び出し可能なオブジェクトを指定すればよさそう。リクエスト毎に呼ばれる call がtrueを返す場合にのみ、対象のルーティングがマッチするといった動作のよう。本投稿では触れていないが matches? でも可。 ( テストコード実装部分 を参照) 

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0