代码之家  ›  专栏  ›  技术社区  ›  krunal shah

保存前在上创建新记录

  •  1
  • krunal shah  · 技术社区  · 15 年前

    创建新记录时。我需要为同一个模型创建更多的记录。

    例子::

    class XYZ < ActiveRecord
     def before_save
       # At this point object is already initialized ..
       # And it's containing values.
       # At this point i want to create 10 more records for the same class.
       # something like this
       XYZ.new(:att1 => value1,:att2 => value2,:att3 => self.att1)
     end
    end
    

    我该如何处理这种情况? 在哪个回拨时,我必须为同一型号创建更多记录?

    2 回复  |  直到 15 年前
        1
  •  2
  •   rafamvc    15 年前

    首先,这听起来像一个糟糕的工程,试着重新思考你的模型,使你需要什么。 如果需要创建10个模型,请不要使用activerecord钩子,否则可能会在infine循环中产生。

    我建议

    class XYZ < ActiveRecord
     def self.create10(original_xyz)
       10.times do
         clone = original_xyz.clone
         clone.save
       end
     end
    end
    

    在您的控制器中或需要创建10个以上的位置,请致电:

    new_xyz = XYZ.new(:att1 => value1,:att2 => value2,:att3 => self.att1)
    new_xyz.save
    XYZ.create10(new_xyz)
    

    但是如果你真的需要在一个钩子上再创建10个(如保存之前),请执行以下操作:

    class XYZ < ActiveRecord
    
     before_save create10
    
     attr_acessor :cloned 
    
     def create10
       return if cloned # this will prevent infinit loooooooooooooooop
       10.times do
         clone = self.clone
         clone.cloned = true
         clone.save
       end
     end
    
    end
    

    我没有做这个,所以,先试试。

        2
  •  0
  •   Sam å±±    15 年前
    class XYZ < ActiveRecord
     def after_initialize
       # At this point object is already initialized ..
       # And it's containing values.
       # At this point i want to create 10 moew records for the same class.
       # something like this
       #XYZ.new(:att1 => value1,:att2 => value2,:att3 => self.att1)
       x = 10 #an integer
       x.times do |task|
         Model.create(:key => :value)
       end
      end
    end
    
    推荐文章