Saturday, March 31, 2007

Is this a good Ruby copy-constructor?

I had the need to copy a model instance in a Rails application I'm writing. I am not a Ruby wizz yet, so I am just going to ask. Is this a good copy-constructor in Ruby/Rails terms?
  def copy_constructor
course = = nil # make copy transient

# the "trainers" n-m relation is not copied in "new", as it is not an attribute on the model
course.trainers = self.trainers
course.trainer_ids = self.trainer_ids

return course
The model I am copying is "Course" and it has a N-M relation to a "Trainer" model. I use the "self.attributes" call, to set attributes on the new instance, but the relations are not copied. Also, I set "id" to nil, to make ActiveRecord think it is transient, which makes ".save" do an insert.

Any better way to do this?