Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with clone method in Rails 3.2

I tried to clone one of my object today, but it seems that its not working like in documentation.

In my console I'm doing:

u = User.find 1
nu = u.clone
nu.new_record?
   => false 
nu.new?
  NoMethodError: undefined method `new?' for #<User:0x007fbf137b8278>

So it looks like cloned object is just a duplicate, because it has the same Id like old one, but according to documentation, it should be new object?

clone()

Returns a clone of the resource that hasn’t been assigned an id yet and is treated as a new resource.

ryan = Person.find(1)

not_ryan = ryan.clone

not_ryan.new? # => true

like image 641
Johny Avatar asked Dec 07 '22 16:12

Johny


1 Answers

According to the docs is deprecated since Rails 2.3.8 and has probably been removed since. So in fact you are calling Object#clone which used to call ActiveRecord::Base#initialize_copy which was removed in Rails 3.0.9.

Use dup instead.

like image 95
Jakub Hampl Avatar answered Dec 20 '22 22:12

Jakub Hampl