Musings from a Southern software developer

Attack of the Clones

This is an elementary Rails tip, but one that I just recently stumbled into. When working in a project where you have a record that you want to make multiple instances of, you can do it the old fashioned way:

Notice that the “x” will be a different value in each loop. Now for the grand finale, you can save all this typing and use a method on an ActiveRecord object called “clone”. From the official Rails docs:

Returns a clone of the record that hasn‘t been assigned an id yet and is treated as a new record. Note that this is a “shallow” clone: it copies the object‘s attributes only, not its associations. The extent of a “deep” clone is application-specific and is therefore left to the application to implement according to its need.

To use this, grab the record you want to clone first:

user = User.find(1)
# "Tureaud">

Note that this does not work on a collection of ActiveRecord objects – only an individual object. Now, call the clone method, and this removes the id attribute: