【问题标题】:Create a copy of an object and all its associated models in rails在 Rails 中创建对象及其所有关联模型的副本
【发布时间】:2013-07-23 19:33:21
【问题描述】:

我正在努力在 rails 及其所有相关的关联模型中创建对象的副本。但我无法找到解决方案。我不想使用像 Amoeba 这样的宝石。模型之间的关系是这样的。

class ClassToCopy
    has_many :cups
    has_many :cup_parts, through :cups
    belongs_to :xyz
end

所以我想保留一个像复制 ClassToCopy 这样的按钮,单击该按钮应该创建该对象的一个​​新副本,其中包含所有关联。就像 ClassToCopy 的对象有 10 个杯子和 4 个杯子零件一样,那么这些类的对应对象也应该被创建。 我尝试过使用 clonedup(使用 rails 3.2.x),但 clone 不会从原始对象创建新对象,并且 dup 不允许关联.因此,我很困惑该怎么做。

【问题讨论】:

    标签: ruby ruby-on-rails-3.2 clone


    【解决方案1】:

    您可以覆盖 dup 以为每个关联返回一个新对象和一个新对象,例如:

    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
    

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2015-01-03
      相关资源
      最近更新 更多