I am working on creating a copy of an object in rails and all its related associated models. But i am unable to figure out a solution for that. I don't want to use any gem like Amoeba. The relationships between the models is something like this.
class ClassToCopy
has_many :cups
has_many :cup_parts, through :cups
belongs_to :xyz
end
So i want to keep a button like copy ClassToCopy and on clicking on that should create a new copy of that object with all the associations along with it. Like if an object of ClassToCopy has 10 cups and 4 cup_parts then corresponding objects of those classes should also be created. I have tried out using clone and dup (using rails 3.2.x), but clone doesn't create a new object from the original one and dup doesn't allow associations. Hence am confused what to do.
You could could override dup
to return a new object and a new object for each of the assosiations, something like:
class Thing
has_many :cups
def dup
super.tap do |new_thing|
self.cups.each do |cup|
new_thing.cups << cup.dup
end
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With