When I built my Rails 3.0.3 application RecordMyRun.com I wisely gave users a choice of recording course distances in kilometers or miles because everyone does not live in the United States and this is the Internet, so. . .
However when I added the ability to record and chart body weight, I got excited and forgot to provide the U.S./metric option. So now I’m going back and adding it. As with distances, I decided I wanted all values stored in the database in metric. If a user has chosen U.S. measurements as her default, then the values are converted from metric when saved or accessed.
But I already have over a month’s worth of weights in pounds stored in my database. I needed to convert these values to kilograms. Writing a script or a rake task was my first thought, but then I remembered the Rails console and realized I could do it there and be done with it. Here’s how I did it:
rails c weights = Weight.all weights.each do |weight| weight.weight_entry = weight.weight_entry * 0.45 weight.save end
Of course I backed up my database before doing this. Because you ALWAYS backup your database before trying something like this.