2016-07-14 11 views
1

レールアクティブなレコードを使用してバルク内のすべてのネストされた属性を挿入します私のパラメータ構造は次のようになりますは、どのように私はこのようなレポートモデルを持っている

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

レポートと2つのクエリを挿入するために1つのクエリが実行されますreport_clientsを挿入します。

一般に、私は1000のSQLクエリにつながる各レポートに対して1000個のreport_clientsを挿入しました。

私はraw SQLインサートを記述することで、一括挿入を使用して問題を解決できます。しかし、それが他の方法/これを行うより良い方法であるかどうかを知りたがっていました。

答えて

0

同様のシナリオを経て、これらのタイプのケースには最高の宝石activerecord-importがあります。

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

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 

report.rbで大量輸入レコードにgem wikiで述べた他の多くの方法があります。

役に立てば幸い!

+0

ありがとうございました。この場合、レポートモデルの検証は機能しますか。 –

+0

はい、検証を実行するので、 'save!'を使うか、 'if save'の下に入れ子のクライアントを追加することができます。私は処理するために 'transaction'ブロックの下にある全てと、他のデータベースエラーを追加しました。 – RSB

+0

ReportClient.import(report_clients_objects)を実行したいとき ***クラスがバリデーションやコールバックなしで多数作成する*** –

関連する問題