motolog

Everything I love in my life.

Railsでカスタムサブドメイン-本サイトとサブドメイン間のURL設定

Railsでサブドメインを実装した際に、本サイトとサブドメインサイト間の受け渡しで少しハマりました。

サブドメインサイトにいる状態で、root_path や root_url でリンク先を指定しても、本サイトではなく、そのサブドメインのトップに飛ばされます。

この記事では、url_for メソッドを利用して、サブドメインサイトと本サイト間を行き来する方法をご紹介します。



url_forでメソッド作成

subdomain_url_helper を以下のように作成

module SubdomainUrlHelper
  def with_subdomain(subdomain)
    subdomain ||= 'www'
    subdomain += "."
    [subdomain, request.domain].join
  end

  # - remove subdomain and go to the original site
  #    url_for(:subdomain => false)
  # - go to the specific subdomain site
  #    url_for(:requested_subdomain => 'subdomain')
  def url_for(options = nil)
    if options.kind_of?(Hash) && options.has_key?(:subdomain)
      options[:host] = with_subdomain(options.delete(:subdomain))
    elsif options.kind_of?(Hash) && options.has_key?(:requested_subdomain)
      options[:host] = with_subdomain(options.delete(:requested_subdomain))
      options[:controller] = 'users'
      options[:action] = 'show'
    end
    super
  end
end

メインは、2つめのurl_forメソッド。
with_subdomainメソッドは、引数の subdomain と request.domain を合わせるためのもの。なお、subdomain が存在しなければ、www が代わりに入る。
そのため、

url_for(:subdomain => false)

とすると、

# if request.domain is "example.com"
www.example.com

のようになる。

url_for については、渡された hashのkey で条件分岐してあるのは、見ての通りです。

コードがなかなか汚いのでだれかリファクタお願いします。

関連記事



© 2018 Motoki Yoshida