Ken J
Ken J

Reputation: 4562

Rails ActiveJob Start From Controller

I have some custom code that calls some backend systems and updates the database remotely. I have an ActiveJob that performs the task:

## Runs join code
class DataJoin < ApplicationJob
  queue_as :default

  def perform
    join = Joiner.new
    join.run
    NotifMailer.sample_email.deliver_now
  end
end

I want to kick off an ActiveJob manually from a controller/view:

class AdminController < ApplicationController
  before_action :verify_is_admin

  private def verify_is_admin
      (current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
  end

  def index
    @username = current_user.name
    @intro = "Welcome to the admin console"
  end

  def join
   ## Code to start ActiveJob DataJoin??
  end
end

How can I kick off an ActiveJob from a controller?

Upvotes: 4

Views: 2445

Answers (2)

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

Please read the official guide on ActiveJob

def join
  DataJoin.perform_later
end

Upvotes: 0

31piy
31piy

Reputation: 23859

Try this:

DataJoin.perform_later

perform_later enqueues the job in the specified queue. If the perform method of your active job accepts some arguments, you can even pass them in perform_later, and those will be available at the time of execution.

DataJoin.perform_later(1, 2, 3)

# DataJoin
def perform(a1, a2, a3)
  # a1 will be 1
  # a2 will be 2
  # a3 will be 3
end

Upvotes: 3

Related Questions