2017-07-28 91 views
0

我有一個是這樣定義的活動記錄關係處理:軌道預取記錄在隊列

contacts = Contact.where("status = 'waiting'") 

然後,我做了以下內容:

if contacts 

    batch_id = randomStringOfLength(32) 

    #Set to processing 
    contacts.update_all(status: 'processing', batch_id: batch_id) 

    #TODO: Is this the best way to do this? 
    contacts = Contact.where("batch_id = ?", batch_id) 

    contacts.each do |contact| 

     executeFor(contact) 

    end 
end 

正如你所看到的,我不得不用特定的batch_id更新記錄,以便以後能夠獲取它們。

這是因爲我的第一個聯繫人實際上並沒有獲取記錄。第一個數據庫調用是更新到狀態processing,然後通過batch_id獲取它們允許我運行每個循環。

有沒有更好的方法來做到這一點?雖然我索引了batch_id,但我認爲在rails中可能會有更好的方法。

如果我不更新batch_id並刪除行以獲取batch_id,那麼.each將不會返回任何內容,因爲狀態以前已更新。

感謝

+0

這個問題是不是與https://stackoverflow.com/questions/45363743? –

+0

@StephanePaquet沒有。謝謝 – Walker

回答

0

如果你不需要在你的數據庫中的batch_id你可以寫:

contacts = Contact.where(status: 'waiting') 
if contacts 

    #Set to processing 
    contacts.update_all(status: 'processing') 

    #TODO: Is this the best way to do this? 
    contacts = Contact.where(status: 'processing') 

    contacts.each do |contact| 
     executeFor(contact) 
    end 
end 

而且這個選項甚至可能會更快一點:

if Contact.where(status: 'waiting').update_all(status: 'processing') > 0 
    contacts = Contact.where(status: 'processing') 

    contacts.each do |contact| 
     executeFor(contact) 
    end 
end 

不要忘記檢查你的數據庫的索引。狀態需要一個。

保持batch_id

batch_id = randomStringOfLength(32) 
if Contact.where(status: 'waiting').update_all(status: 'processing', batch_id: batch_id) > 0 
    contacts = Contact.where(batch_id: batch_id) 

    contacts.each do |contact| 
     executeFor(contact) 
    end 
end 
+0

嗨Stephane,謝謝你的答案。但是,如果另一個隊列當前正在運行,則可能會出現問題。我不能假定所有正在處理的記錄都屬於當前批次。說得通? – Walker