LoginSignup
1
1

More than 5 years have passed since last update.

URLパスの一部に引数を含める書き方をするときにasオプションで作った名前を使う利点

Last updated at Posted at 2017-11-27

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 の不具合です。

1
1
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
1
1