2016-07-14 119 views
1

我有一個報表模型這樣的插入所有散裝嵌套屬性創建我的參數結構將會像如何使用Rails的活動記錄

Report.create({name: params[:name], report_clients_attributes: [{client_id: 1}, {client_id:2}]}) 

它會運行1個查詢插入報告和2個查詢插入report_clients。

通常我用來插入1000 report_clients針對每個導致1000 sql查詢的報告。

我知道,我可以通過編寫原始sql插入使用批量插入來解決問題。但想知道,是否有其他方式/更好的方式來做到這一點。

回答

0

通過類似的情況,有一個真棒寶石activerecord-import這些類型的案件。

report = Report.new(name: params[:name]) 
report.save_with_nested_attributes(report_clients_attributes) 

report.rb

def save_with_nested_attributes(report_clients_attributes) 
    report_clients_objects = [] 
    transaction do 
    save! 
    report_clients_attributes.each do |client_attributes| 
     report_clients_objects << report_clients.new(client_attributes)  
    end 
    ReportClient.import(report_clients_objects) 
    end 
end 

有在gem wiki提到大衆進口記錄許多其他的方法。

希望有幫助!

+0

感謝@RSB的幫助。在這種情況下,報告模型驗證是否可行? –

+0

是的,它運行驗證,您可以使用'save!'或在'if save'下添加嵌套客戶端。我在'transaction'塊下添加了一切以處理和其他數據庫錯誤。 – RSB

+0

當我想運行ReportClient.import(report_clients_objects) 它顯示 ***類創建許多沒有驗證或回調*** –