2010-10-14 81 views
1

創建新記錄時。我需要爲同一模型創建更多記錄。在before_save上創建新記錄

例::

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 

請問有什麼可以處理這種情況的? 在哪個回調中,我必須爲同一個模型創建更多記錄?

+0

你是否也希望爲那些*觸發before_save? – 2010-10-14 19:10:47

+0

@馬克托馬斯是驗證和回調需要對那些火。 – 2010-10-14 19:15:02

+0

你打算如何阻止before_saves創建的無限循環被before_saves創建的額外記錄調用? – 2010-10-14 19:19:10

回答

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 

我沒有運行這個,所以,先試一下。

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 
+0

但是在創建其他對象之前,我需要檢查現有對象的驗證。驗證和回調也需要在其他記錄上觸發。 – 2010-10-14 19:18:13

+0

你爲什麼要創建Model的實例? OP想要新的XYZ。 '任務'也是不必要的,參考10次。10.times {}很好。 – 2010-10-14 19:19:25

+0

@Dave我有一個任務,如果用戶將輸入一個記錄,而不是在後臺,我必須將該記錄分佈在另外10行中。一行用戶輸入,另外10行用於計算的行。那麼我該如何處理這種情況呢? – 2010-10-14 19:26:24