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:

User.create(:first_name => 'Laurence;', :last_name => 'Tureaud', :alias => 'Mr. T')

However, this is quite a bit of typing. If you want multiple users, you can add a loop structure like this:

(1..5).each {User.create(:first_name => 'Laurence;', :last_name => 'Tureaud', :alias => 'Mr. T')}

This will create 5 Mr. T’s! Of course, if you have any validations checking for unique values, this might fail. I would recommend using the loop structure to prefix, or postfix a unique digit:

(1..5).each {|x| User.create(:first_name => 'Laurence;', :last_name => "Tureaud#{x}", :alias => 'Mr. T')}

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:

user = User.find(1)
# "Tureaud">
new_user = user.clone
# "Tureaud">
new_user.save
true

I have now cloned my object. With some method chaining, and some looping, we can easy mass create fake records:

user = User.find(1)
# "Tureaud">
(1..5).each {user.clone.save}

Much less typing! Now, with all that time you saved, go sign up for an Amazon Prime account and buy some cool stuff and get it shipped for free!

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.