Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a copy of an object and all its associated models in rails

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.

like image 536
Jimmy Thakkar Avatar asked Oct 22 '22 04:10

Jimmy Thakkar


1 Answers

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
like image 109
Kris Avatar answered Oct 30 '22 15:10

Kris