2017-07-18 71 views
0

我正在使用delayed_jobs gem。假設,我有一個ArticleController與BackgroundJobs.rb如何添加兩個延遲工作

class BackgroundJobs < ActiveRecord::Base 
    def sendmail(article_id) 
    #code to send mail 
    end 

def createpdf((article_id)) 
    #code to generate pdf  
end 

end 

我怎樣才能在articlecontroller代碼添加了發送郵件和createpdf方法來延遲工作下面的代碼

@articles.each do |ar| 
    #call send mail method and add to delay 
    #call createpdf method and add to delay 

    end 

和其他類。

回答

1

首先,我會創造方法,而不是實例方法BackgroundJobs

class BackgroundJobs < ActiveRecord::Base 
    def self.sendmail(article_id) 
    #code to send mail 
    end 

    def self.createpdf(article_id) 
    #code to generate pdf  
    end 
end 

然後就是直接給他們打電話控制器:

@articles.each do |ar| 
    BackgroundJobs.delay.sendmail(ar.id) 
    BackgroundJobs.delay.createpdf(ar.id) 
end 
+0

由於'BackgroundJobs'似乎除了執行這兩種方法之外沒有其他功能,您可以考慮將它們轉換爲服務。 – Gerry