Search code examples
ruby-on-railsdeep-copy

Ruby on Rails deep copy/ deep clone of object and its attributes


I would like to do a deep copy on objects including all the attributes.

The experiment_old is has 10 trials. And I want to copy everything to experiment_new with the 10 trials. experiment_old should also keep the 10 trial info.

However, all the cases I tried below, they copy everything well, but experiment_old does not have the 10 trials info. They just show up on experiment_new.

What is the best way to do deep copy for these cases.

case 1:

@experiment_new = Experiment.create(@experiment_old.attributes.merge(:trials => experiment_old.trails))

case 2:

@experiment_new = Marshal.load(Marshal.dump(@experiment_old.trials))

case 3:

@experiment_new = @experiment_old.clone

Here is the model:

class Experiment < ActiveRecord::Base
  belongs_to :experimenter
  has_many :trials
  has_many :participants
end


class Trial < ActiveRecord::Base
  belongs_to :experiment
  belongs_to :datum
  belongs_to :condition
  has_one :result_trial
end

Solution

  • You should clone every trial and assign them to the cloned experiment:

    @experiment_new = @experiment_old.clone
    @experiment_old.trials.each do |trial|
      @experiment_new.trials << trial.clone
    end