as
オプションで作った名前を利用すると環境変数 RAILS_RELATIVE_URL_ROOT
を反映させることができます。
ENV["RAILS_RELATIVE_URL_ROOT"] = "/subdir"
require "action_controller/railtie"
require "action_dispatch/routing/inspector"
Rails::VERSION::STRING # => "5.1.4"
app = Class.new(Rails::Application)
app.routes.draw do
get "search1/:key", to: "xxx#show"
get "search2/:key", to: "xxx#show", as: :search2
end
include Rails.application.routes.url_helpers
formatter = ActionDispatch::Routing::ConsoleFormatter.new
puts ActionDispatch::Routing::RoutesInspector.new(Rails.application.routes.routes).format(formatter)
# >> Prefix Verb URI Pattern Controller#Action
# >> GET /search1/:key(.:format) xxx#show
# >> search2 GET /search2/:key(.:format) xxx#show
url_for("/search1/rails") # => "/search1/rails"
url_for([:search2, key: "rails", only_path: true]) # => "/subdir/search2/rails"
- パスを文字列で書いた
url_for("/search1/rails")
では環境変数で指定した相対パスが含まれない - 一方
as
で指定した名前を使ったsearch2
の方には含まれている
なお、as
を指定して生まれた search2_path
を利用すると次のようになります。
search2_path(key: "rails") # => "/subdir/search2/rails"
search2_path("rails", "png") # => "/subdir/search2/rails.png"
search2_path("rails") # => "/search2/rails"
最後の書き方だけ相対パスが反映されていないのは Rails の不具合です。