Problems with the clone method in Rails 3.2

I tried to clone one of my objects today, but it seems that it does not work, as in the documentation.

In my console, I do:

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

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

clone ()

Returns a clone of a resource that has not yet been assigned an identifier, and is treated as a new resource.

ryan = Person.find (1)

not_ryan = ryan.clone

not_ryan.new? # => true

+4
source share
2 answers

According to the docs, they are deprecated with Rails 2.3.8 and have probably been deleted since then. Therefore, you are actually calling Object # clone , which was used to call ActiveRecord :: Base # initialize_copy , which was removed in Rails 3.0.9.

Use dup .

+14
source

This is an ugly version for updates: calling 'clone' will not throw an error or anything else - it will just return the original model. Thus, any code that you wrote that should duplicate some model and make changes to a new copy will silently modify the original instead!

+1
source

Source: https://habr.com/ru/post/1393428/


All Articles