Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Clone records

How do i and is it possible clone records and it's associated records?

Example.

Category
_| Product
___
| Product variant

So, when i click a button, the category, products and product variants is cloned/copied.

Thanks...

like image 826
andkjaer Avatar asked Apr 09 '26 11:04

andkjaer


1 Answers

You must overwrite #clone so that all associations are also cloned, like

class Category < ActiveRecord::Base
  has_many :products

  alias_method :original_clone, clone

  def clone
    category = self.original_clone
    category.products = self.products.clone
  end
end

... remember to do the same on Product and ProductVariant.

like image 71
Pablo Avatar answered Apr 12 '26 08:04

Pablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!