Reputation: 1316
I have a Post model (below) which has a callback method to modify the body attribute via a delayed job. If I remove "delay." and just execute #shorten_urls! instantly, it works fine. However, from the context of a delayed job, it does NOT save the updated body.
class Post < ActiveRecord::Base
after_create :shorten_urls
def shorten_urls
delay.shorten_urls!
end
def shorten_urls!
# this task might take a long time,
# but for this example i'll just change the body to something else
self.body = 'updated body'
save!
end
end
Strangely, the job is processed without any problems:
[Worker(host:dereks-imac.home pid:76666)] Post#shorten_urls! completed after 0.0021
[Worker(host:dereks-imac.home pid:76666)] 1 jobs processed at 161.7611 j/s, 0 failed ...
Yet, the body is not updated. Anyone know what I'm doing wrong?
-- EDIT --
Per Alex's suggestion, I've updated the code to look like this (but to no avail):
class Post < ActiveRecord::Base
after_create :shorten_urls
def self.shorten_urls!(post_id=nil)
post = Post.find(post_id)
post.body = 'it worked'
post.save!
end
def shorten_urls
Post.delay.shorten_urls!(self.id)
end
end
Upvotes: 4
Views: 1290
Reputation: 6044
One of the reasons might be that self
is not serialized correctly when you pass method to delay
. Try making shorten_urls!
a class method that takes record id and fetches it from DB.
Upvotes: 1