Rails 克隆记录

发布于 2024-10-10 02:22:40 字数 179 浏览 0 评论 0原文

我如何以及是否可以克隆记录及其关联记录?

例子。

类别
_| 产品
___
| 产品变体

因此,当我单击按钮时,类别、产品和产品变体将被克隆/复制。

谢谢...

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

掩耳倾听 2024-10-17 02:22:40

您必须覆盖#clone,以便所有关联也被克隆,例如

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

...记住对 Product 和 ProductVariant 执行相同的操作。

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.

霊感 2024-10-17 02:22:40

我认为你应该从使用“克隆”方法开始。如果我理解正确的话,你的问题是你想要一个递归克隆。坦率地说,我不知道它是否存在通用解决方案,但我认为你可以手动克隆你的父子链。也许这不是一个优雅的解决方案,但它应该有效。

I think you should start from using "clone" method. Your problem, if I have understood it right, is that you want a recursive clone. Frankly, i don't know if it exists a general solution but I think you could clone you father/sons chain by hand. Maybe it isn't an elegant solution but it should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文