4

サブドメイン RailsCastからコードを取得します

module UrlHelper
  def with_subdomain(subdomain)
    subdomain = (subdomain || "")
    subdomain += "." unless subdomain.empty?
    [subdomain, request.domain, request.port_string].join
  end

  def url_for(options = nil)
    if options.kind_of?(Hash) && options.has_key?(:subdomain)
      options[:host] = with_subdomain(options.delete(:subdomain))
    end
    super
  end
end

class ApplicationController < ActionController::Base
  include UrlHelper
end  

url_forコントローラーのビューで変更を使用しても問題ありません。しかし、私は ActionMailer に問題があります。

私は以下を使用しようとしました:

class Notifier < ActionMailer::Base
  include UrlHelper
end

しかし、ActionMailer のビューは、ActionDispatch::Routing::RouteSet の古い変更されていない url_for を引き続き使用します。

新しい url_for を追加するベスト プラクティスは何ですか

4

3 に答える 3

5

次のコードをファイル app/helpers/url_helper.rb に追加します。

def set_mailer_url_options
    ActionMailer::Base.default_url_options[:host] = with_subdomain(request.subdomain)
end

ファイル app/controllers/application_controller.rb を変更して以下を追加します。

before_filter :set_mailer_url_options

ソース

于 2011-05-11T05:50:15.997 に答える
1

この問題の解決策はありますが、それでも最善の方法ではないと思います。私は試してみましたが、より良い解決策を考え出すつもりですが、メールテンプレートで行ったことは次のとおりです. これをメールのテンプレートに入れているのは、Devise を使用しているためですが、より良いものを考え出すことを望んでいます。

subdomain = @resource.account.subdomain
subdomain = (subdomain || "")
subdomain += "." unless subdomain.empty?
host = [subdomain, ActionMailer::Base::default_url_options[:host]].join

このようにホストを url_for に渡すことができます

user_confirmation_url(:host => host)
于 2010-11-18T15:00:36.110 に答える
0

Rails 3.0.xで最も簡単な解決策は、メーラービューのすべてのURLでhost-with-subdomainを手動で作成することでした。例えば:

Your account is here:

<%= account_url(:host => "#{@account.subdomain}.#{ActionMailer::Base.default_url_options[:host]}" %>

-@accountモデルがそのサブドメインを知っている場合。

これは素晴らしく、シンプルで、スレッドセーフで、分離されています。コードベースの他の部分を汚染する必要はありません。そして、Rails 3.1.xに移行すると、簡単に元に戻すことができます。これにより、これらすべてが自動的に処理されるはずです。

于 2011-10-07T14:00:52.640 に答える