Thursday, September 10, 2009

Cloning/copying Data in Database Corresponding to ActiveRecord Objects in Rails

Richard O. provided a script this morning that does a shallow clone of an example ActiveRecord object in the database. Here is an example based on his example. There is a group of objects (we'll call them SomeProducts) that they want to clone at the end of each time period (we'll call it ModelYear) to create new instances where the time period (ModelYear) is set. This example only works for shallow cloning (it isn't cloning any attribute objects of SomeProduct that might have their own ids in the DB). There are many other ways to do versioning (and Paul explored new scoping stuff in Rails 2.3 also), but this was the method chosen, and I'm mostly just providing this example to show how easy it is to shallow clone a set of ActiveRecord object in Rails and save them to the DB.

CURRENT_MODEL_YEAR="2009"
NEW_MODEL_YEAR="2010"

if SomeProduct.all(:conditions => ["model_year_id = ?",  ModelYear.find_by_year(NEW_MODEL_YEAR).id]).empty?
  SomeProduct.all(:conditions => ["model_year_id = ?",  ModelYear.find_by_year(CURRENT_MODEL_YEAR).id]).each do |gp|
    new_prod = SomeProduct.new(gp.attributes.except("id"))
    new_prod.model_year_id = ModelYear.find_by_year(NEW_MODEL_YEAR).id
    new_prod.save
  end
else
  puts "SomeProducts already exist for #{NEW_MODEL_YEAR}"
end

No comments: