I have three different API calls happening when a record is created.
1) Call to create a bitly URL for the record. 2) Call to post to facebook with the bitly URL 3) Call to post to twitter with the bitly URL
My current process is as follows:
On record Create and Update
respond_to do |format|
if @dealer.save
call_bitly_api
end
end
in my model:
after_save :social_media_posting
def social_media_posting
if (self.bitly_url.present? && self.posted_to_facebook == false)
call_facebook_post
end
if (self.bitly_url.present? && self.posted_to_twitter == false)
call_twitter_post
end
end
The issue that I am facing is that the facebook and twitter post is being called on first save where the bitly_url is not yet created.
Need help is figuring out how to add these calls that they can still happen yet they happen in order and wait for the bitly_url to be present before the call the facebook and twitter is made? Major thing worth mentioning I am using sidekiq to make the calls and send the actual call to the sidekiq worker to work in the background.
In controller:
CallBitlyWorker.perform_async(dealer.id)
In your worker:
class CallBitlyWorker
include Sidekiq::Worker
def perform(dealer_id)
dealer = Dealer.find(dealer_id)
# make bitly call
dealer.update_attribute(:bitly_url, some_url)
# make the social media calls in parallel
CallFacebook.perform_async(dealer_id)
CallTwitter.perform_async(dealer_id)
end
end
ActiveRecord callbacks should be avoided where possible. They just make your code more opaque.