Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate a record in Rails except for one attribute?

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 ?

like image 755
Tintin81 Avatar asked Sep 18 '25 03:09

Tintin81


1 Answers

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.

like image 141
Henrik N Avatar answered Sep 19 '25 18:09

Henrik N