Recreate All Your Records

 Jan 18, 2013

This may seem like a pretty unlikely situation, but occasionally you may need to recreate all records in a particular table, and you want it done via ActiveRecord

The exact reason for my attempting this, is that I recently added the friendly_id gem to my blog to make the URL’s to articles use the article title rather than the normal format of /:model/:id

I watched Ryan Bates RailsCast for doing this, and included the history option so that if I change slugs, the old links don’t end up broken

One of the caveats that Ryan mentions in his cast is that the history setup only works for newly created records, anything already in the system won’t be added to the history.

So, heres a little snippet of code that will sort that out for you. Either in the rails console for your app or you could use a migration

Article.find_each do |article|
  replacement = article.dup
  replacement[:id] = nil
  replacement.save
end

There may be other ways, better ways, more idiomatic ways to achieve this result, but this worked for me

By the way, if you haven’t checked out RailsCasts by Ryan Bates, I really recommend that you do. I’ve followed along with the free videos for a while, but there is just too much good stuff on there to not drop the $9 a month for the Pro subscription. Really do check it out if you have any interest in Rails.