2012-09-07 49 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]