Ruby on Rails对象及其属性的深层复制/深层克隆 [英] 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.
experiment_old进行了10次试验。我想通过10个试验将所有内容复制到experiment_new。 Experiment_old还应保留10个试用信息。
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.
但是,我在下面尝试的所有情况下,它们都能很好地复制所有内容,但是experiment_old没有10条试验信息。它们只是出现在experiment_new上。
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.
情况1:
@experiment_new = Experiment.create(@experiment_old.attributes.merge(:trials => experiment_old.trails))
情况2:
@experiment_new = Marshal.load(Marshal.dump(@experiment_old.trials))
情况3:
@experiment_new = @experiment_old.clone
这里是模型:
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
推荐答案
您应该克隆每个试验并将它们分配给克隆的试验:
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
这篇关于Ruby on Rails对象及其属性的深层复制/深层克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!