Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone (a.k.a. duplicate) a Record

I need to duplicate a record, with the same attributes of the original except ID of cource. I do:

In the View:

<%= link_to "Duplicate", :action => "clone", :id => Some_Existing_ID %>

And in the Controller:

def clone
  @item = Item.find(params[:id]).clone

  if @item.save
    flash[:notice] = 'Item was successfully cloned.'
  else
    flash[:notice] = 'ERROR: Item can\'t be cloned.'
  end

  redirect_to(items_path)
end      

But nothing happens! In Console I figured out that clone generates the copy without ID.

Any ideas ?

*> BTW: I am running Rails 2.3.5 and Ruby 1.8

like image 762
Ben Orozco Avatar asked Jan 15 '10 08:01

Ben Orozco


1 Answers

Avoid using the clone method. It is no longer supported. The clone method now delegates to using Kernel#clone which will copy the id of the object.

# rails < 3.1
new_record = old_record.clone

# rails >= 3.1
new_record = old_record.dup
like image 135
Hendrik Avatar answered Sep 19 '22 21:09

Hendrik