LoginSignup
15
12

More than 5 years have passed since last update.

動的にdefault_url_options[:host]をセットする

Last updated at Posted at 2016-11-24
Missing host to link to! Please provide the :host parameter, set default_url_options[:host]

というエラーに対処した話。Controllerなど以外ではrequestの情報がないので:hostを別途指定しないといけない。

やりたいこととしてはroot_urlをController以外で使いたかったから。具体的にはWebhookで投げるテキストにURLを含めたかった。

module Webhooks
  class Send
    include Rails.application.routes.url_helpers #root_urlを使うため。

    def initialize
    end

    def call
      url = root_url
    end
  end
end

普通はというかホスト名が決め打ちできるならAction Mailer の基礎 | Rails ガイドにあるように、config/application.rbに書くのがいいようだが、今回はそうではない。
しかたがないのでApplicationControllerでセットするようにした

class ApplicationController < ActionController::Base
  before_filter :set_host

  def set_host
    Rails.application.routes.default_url_options[:host] = request.host_with_port
  end
end
15
12
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
15
12