Ruby on rails with active record perfomance
The #dups are probably unnecessary. If you unset the ID ActiveRecord already "thinks" that the object is new, and #save will create a new one in the DB. But the main bottleneck is probably the amount of DB queries generated. The easiest way to gain some performance in such cases is to wrap the whole block into a transaction. The best way would probably use bulk inserts (e.g. with a gem like https://github.com/zdennis/activerecord-import).

But if you've to do so many deep copies you also should rethink if you're using the right approach (or DB) here.