Calling url_helpers from Rails ActiveJob
This article was automatically translated from Japanese by AI. Read the original Japanese version →
Table of Contents
Here is how to call *_url helpers from inside a Rails ActiveJob.
When Do You Need This?
For example, when a job calls an external API and needs to pass a callback URL as one of its parameters.
How to Do It
- Include
url_helpers - Override
default_url_options(without this, Rails will complain that it doesn't know the host name) - Optionally create a
BaseJoband haveHogeJobinherit from it
# 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