5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ルーティングの定義で外部URLも自然に書けるdirectメソッドの使い方

Posted at
require "action_controller/railtie"
ActionPack::VERSION::STRING     # => "5.1.4"

Class.new(Rails::Application).routes.draw do
  direct :google do |options|
    "https://www.google.co.jp/?q=#{options[:query]}"
  end
end

include Rails.application.routes.url_helpers

url_for(:google)                   # => "https://www.google.co.jp/?q="
url_for([:google, query: "rails"]) # => "https://www.google.co.jp/?q=rails"
google_url                         # => "https://www.google.co.jp/?q="
google_url(query: "rails")         # => "https://www.google.co.jp/?q=rails"
google_path                        # => "/?q="
google_path(query: "rails")        # => "/?q=rails"

Rails4 まで routes.rb にはアプリ内だけのルーティングを書く感じでしたので、外部URLの場合はどこに書いていいか悩ましいところでした。Rails5 からは routes.rb に集約できるようになっていました。

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?