0

Basically Im running a rake task to update the "notes" field in my rails 3 app. Currently I have my task set up as follows:

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

The problem is I have about 250 unique categories to update with 250 unique notes, so I've basically just copied this over 250 times in my task. How can I more efficiently accomplish this? (This is just a one time thing, but I would like to know how to better do it for future issues such as this).

Yogzzz
  • 2,735
  • 5
  • 36
  • 56

2 Answers2

2

take this: 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

run as: rake get_notes[123456]

Community
  • 1
  • 1
sumskyi
  • 1,827
  • 13
  • 13
0

I ended up just creating a function:

  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

and just called the function with each of the unique variables:

desc "Update note"
  task :get_notes => :environment do
    add_note('7818797', "<note>")
end
end
Yogzzz
  • 2,735
  • 5
  • 36
  • 56
  • If you have an array of category ids and an array of notes you could use the Array [zip](http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-zip) method to join them together and call add_note inside the each block. – Andrew Kothmann Sep 07 '12 at 21:47