2012-09-07 48 views
0

基本上我正在運行rake任務來更新我的rails 3應用程序中的「筆記」字段。目前,我有我的任務設置如下:需要幹起我的耙子任務

desc "Update notes" 
    task :get_notes => :environment do 
     Product.find(:all, :conditions => ["categories like ?", "%" + '123456' + "%"]).each do |product| 
     old_note = product.notes 
     notes = old_note + ", <new note>" 
     product.update_attribute(:notes, notes) 
    end 

的問題是我有大約250獨特的類別,有250個獨特的筆記進行更新,所以我基本上只是在我的任務複製這個超過250倍。我怎樣才能更有效地完成這件事? (這只是一次性的事情,但我想知道如何更好地爲未來的問題做到這一點)。

回答

0

最後我只是創造一個功能:

def add_note(category, note) 
    Product.find(:all, :conditions => ["categories like ?", "%" + category + "%"]).each do |product| 
    old_note = product.notes 
    if old_note != nil 
    notes = old_note + note 
    else notes = note 
    end 
    product.update_attribute(:notes, notes) 
    end 
end 

,只是調用每個唯一變量的函數:

desc "Update note" 
    task :get_notes => :environment do 
    add_note('7818797', "<note>") 
end 
end 
+0

如果您有一個類別ID和一系列註釋的數組,您可以使用Array [zip](http://www.ruby-doc.org/core-1.9.3/Array.html#method-i- zip)方法將它們連接在一起並在每個塊內調用add_note。 –

2

藉此:How to pass command line arguments to a rake task

task :get_notes, [:category] => :environment do |t, args| 
    Product.find(:all, :conditions => ["categories like ?", "%#{args[:category]}%"]).each do |product| 
    old_note = product.notes 
    notes = old_note + ", <new note>" 
    product.update_attribute(:notes, notes) 
end 

運行方式:rake get_notes[123456]