views:

31

answers:

2

While creating new records. I need to create more records for the same model.

Example ::

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

How may i handle this type of scenario ? On which call back i have to create more records for the same model ?

A: 
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
Sam
@Sam But Before creating other objects i need to check validation for existing object. And Validations and Callbacks needs to be fire on other records too.
krunal shah
Why are you creating instances of Model? OP wants new XYZs. 'task' is also unecessary, as is a reference to 10. 10.times {} is fine.
Dave Sims
@Dave I have a task like if user will enter one record than in the background i have to distribute that record in 10 more rows. One row for user entered and 10 other rows for calculated ones. So how may i handle that type of scenario ?
krunal shah
+2  A: 

First, this sounds like bad engineering, try to rethink your model in a way that makes what you need. maybe if you need to create 10 models of something, do not use the activerecord hooks, otherwise you might incur in infine loops.

I would recommend

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

and where in your controller or wherever you have the need to create 10 more, call:

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

but if you really need to create 10 more on a hook (like before save), do:

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

I did not run this, so, try it first.

rafamvc