4
4

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.

[Rails]ActiveJobからurl_helperを呼ぶ

Posted at

RailsのActiveJob内から*_urlヘルパーを呼ぶ方法です。

どんなときに使う?

Jobから何かしらのAPIにアクセスして、そのパラメータにcallbackアドレスを設定する場合など

やり方

  1. url_helpersをinclude
  2. default_url_optionsをoverride(これをしないとhost名がわからないよって怒られる)
  3. お好みでBaseJobを作ってそれを継承する形でHogeJobを作成する
app/jobs/base_job.rb
class BaseJob < ActiveJob::Base
  include Rails.application.routes.url_helpers

  protected

  def default_url_options
    { host: ENV['HOST_NAME'] }
  end
end
app/jobs/hoge_job.rb
class HogeJob < BaseJob
  queue_as :default

  def perform(*args)
    # something
    # foobar_urlが呼べる
  end
end
4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?