2

サブドメインとしてユーザーアカウントを使用してデバイスRailsアプリを構築するユーザーがアクセスするサブドメインが存在しない場合に、デフォルト(default.domain.com)サブドメインにリダイレクトする方法を理解できません。

例えば:

  • user.domain.comは機能します(ユーザーはデータベースに存在します)
  • user2.domain.comは失敗し(ユーザーがデータベースにない)、default.domain.comにリダイレクトする必要があります

これはどのように達成できますか?以下のコードを使用していますが、Rails.envに基づくリダイレ​​クトは無限ループになります:(

class ApplicationController < ActionController::Base
  protect_from_forgery

  layout "application"
  before_filter :account

  def account
    @user     = User.where(:subdomain => request.subdomain).first || not_found
  end

  def not_found
      # next 2 lines is a temp solution--- >
      raise ActionController::RoutingError.new('User Not Found')
      return

      # --- > this below fails results in endless loop
      if Rails.env == "development"
        redirect_to "http://default.domain.dev:3000"
        return
      else
        redirect_to "http://default.domain.com"
      end
    end
end
4

1 に答える 1

3

これを行うための特に優れた方法があるかどうかはわかりません。全体像を見ずにここで適切な判断を下すのは簡単ではありませんが、デフォルトドメインを定数としてどこかに保存し、リダイレクトする前にこれを確認する必要があります。いわばループを壊すために!

このようなものの方が良いでしょう。

class ApplicationController < ActionController::Base
  protect_from_forgery

  layout "application"
  before_filter :account

  def account
    @user = User.where(:subdomain => request.subdomain).first

    if @user.nil? and DEFAULT_URL =~ request.subdomain
      port = request.server_port == 80 ? '' : ":#{request.server_port}"
      redirect_to "http://#{DEFAULT_URL}#{port}"
    end
  end

end

一般的な考え方がわかります。初期化子でDEFAULT_URLを設定できます。

于 2012-12-11T07:50:07.997 に答える