Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Job attributes in ActiveJob callback methods?

Rails 4.2, active_jobs, callback_methods

In the perform method of a custom Job I created a new record (and upload a file to S3). How can I pass, or get, that new records id in the after_perform callback? I want to send an email after_perform with a link to the S3 document...but, not sure how to get the id inside the after_perform method. According to the docs you can use job.attributes, but I get 'undefined method attributes'.

I could move the mailer call into the perform method, but Id rather handle it correctly using callbacks. I am unsure how to access attributes (or where those attributes originate) outside of the perform method.

I tried to do some detective work (to determine what attributes were available to the callback) by placing this in the callback:

 puts "job: #{ job }"

or

puts "job: #{ job.attributes }"

or

puts "job: #{ job.attributes.first }"

none of these worked, and all resulted in undefined 'attributes'.

like image 732
hellion Avatar asked Apr 13 '15 04:04

hellion


1 Answers

You have to use arguments instead of attributes:

after_perform do |job|
    record = job.arguments.first
    # Do something with the record
end

Where my perform method looks like:

def perform(record)
    # Perform stuff
end
like image 76
Peter Avatar answered Oct 20 '22 23:10

Peter