2017-07-20 7 views
0

私はこれら2つのテーブルのインストールとクライアントを持っています。 インストールがあれば(私は、関連するクライアントのユーザ名とLINK_TO_PROFILEを含む万件のインストールレコードがあるだろうしたCSVファイルを生成する必要が周りに400kのクライアントRAM使用量100万レコードのcsvを生成しようとすると99%Rails

class Installation < ApplicationRecord 
    belongs_to :client, optional: true 
end 

class Client < ApplicationRecord 
    has_many :installations 
end 

で、万レコードの周りに持っています本)

CSVを生成するコードが

require 'csv' 
    def self.generate_csv 
    attributes = %w{ app_identifier app_name device_type installation_id app_version time_zone created_date updated_date username link_to_profile } 

     CSV.generate(headers: true) do |csv| 
     csv << attributes 

     Installation.all.each do |installation| 
     data = [installation.app_identifier, installation.app_name , installation.device_type , installation.db_id , installation.app_version , installation.time_zone , installation.created_date , installation.updated_date ] 
     if installation.client.present? 
      data << installation.client.username 
      data << installation.client.link_to_profile 
     end 
     csv << data 
     end 
    end 
    end 
であります

各インストールでは、それぞれのクライアント(存在する場合)もロードされ、そのユーザー名とlink_to_profileを取得します。

私はgenerate_csvを呼び出しますと、RAMの使用率は20%です。 Lacレコードのようにしばらくしてから、それは約99.7%に達し、スワップは50%になり、システムはハングし、それ以上の処理は行われません。

ここで問題とはどのように解決できますか?

+0

はあなたが[バッチ](http://api.rubyonrails.org/classes/ActiveRecord/Batches.html)をチェックアウトしたことがありますか? – jvillian

+0

は試してみませんでしたが、熱心な読み込みがありました –

答えて

2

あなたは、いくつかの熱心な積載てみてください:

require 'csv' 
def self.generate_csv 
    attributes = %w{ app_identifier app_name device_type installation_id app_version time_zone created_date updated_date username link_to_profile } 

    CSV.generate(headers: true) do |csv| 
    csv << attributes 

    Installation.includes(:client).each do |installation| 
     data = [installation.app_identifier, installation.app_name , installation.device_type , installation.db_id , installation.app_version , installation.time_zone , installation.created_date , installation.updated_date ] 
     if installation.client 
     data << installation.client.username 
     data << installation.client.link_to_profile 
     end 
     csv << data 
    end 
    end 
end 
+0

申し訳ありませんが、私のコードの一部を変更しましたか? –

+0

もう1つ、Installation.find(:all、:include =>:clients)を検索して試しましたが、エラー –

+0

'Installation.includes(:client).'と' if installation.client' –

関連する問題