In my Rails application I have a method that duplicates an invoice including its items.
class Invoice < ActiveRecord::Base
  def duplicate
    dup.tap do |new_invoice|
      new_invoice.date = Date.today
      new_invoice.number = nil              <<<--------------
      items.each do |item|
        new_invoice.items.push item.dup
      end
    end
  end
end 
Now what I would like is to not copy the number attribute at all, so a new number can be generated inside my new action (I am not showing that here for brevity).
Right now, I am setting it to nil which is not what I want.
Any Ideas ?
Something along these lines perhaps:
def duplicate
  new_invoice = Invoice.new(attributes.except("id", "number"))
  items.each do |item|
    new_invoice.items.push item.dup
  end
  new_invoice
end
Or loop over the attributes if you need to get around protected attributes etc. But self.attributes with Hash#except is probably what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With