在before_save上创建新记录

时间:2010-10-14 19:03:05

标签: ruby-on-rails ruby callback

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

示例::

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 个答案:

答案 0 :(得分:2)

首先,这听起来像糟糕的工程,尝试以一种能够满足您需求的方式重新思考您的模型。 也许如果你需要创建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

我没有运行它,所以,先试试。

答案 1 :(得分:0)

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