0

Rails 3.2.13 アプリでは、多数の関連オブジェクトを持つ Order データの API をクエリし、それをデータベースに保存する必要があります。一部のレコードは既に存在する可能性があるため、存在する場合は更新し、新しい場合は作成します。一度に何千ものレコードをインポートしています。

import メソッドを使用してパフォーマンスを最適化するために、activerecord-import gem を調べていて、以下のコードを思いつきました。

def add_details(order, tax_lines)
  tax_lines.each do |shopify_tax_line|
    taxlines_updated << Taxline.where(:order_id => order.id).first_or_initialize(
      :price => tax_line.price,
      :rate => tax_line.rate,
      :title => tax_line.title)
  end
  Taxline.import taxlines_updated, :validate => false
end

問題は、レコードが既に存在する場合は更新されず、レコードが新しい場合にのみ属性を更新することです。

各レコードで「見つかった場合 -> 属性を更新」または「見つからない場合 -> 新規」のように機能させるにはどうすればよいですか?

どうもありがとう!

4

3 に答える 3

0

これは最終的に使用したコードです。おそらく最も効率的ではありませんが、機能します。

def add_details(shopify_orders)
    tax_lines = []
    shopify_orders.each do |shopify_order|
      shopify_order.tax_lines.each do |shopify_tax_line|
        tax_line = Taxline.where(:order_id => shopify_order.id).first_or_initialize
        tax_line.price = shopify_tax_line.price
        tax_line.rate = shopify_tax_line.rate
        tax_line.title = shopify_tax_line.title
        tax_lines << tax_line
      end
    end
    TaxLine.import tax_lines, :validate => false
end
于 2013-09-24T07:13:40.097 に答える
0

:synchronizeオプションが機能する可能性があります

 def add_details(order, tax_lines)
      taxlines_updated = []
      tax_lines.each do |shopify_tax_line|
        taxlines_updated << Taxline.where(:order_id => order.id).first_or_initialize(
               :price => tax_line.price,
               :rate => tax_line.rate,
                :title => tax_line.title)
      end
      Taxline.import taxlines_updated, :validate => false, :synchronize => taxlines_updated
  end

gemドキュメントの場合

    # * +synchronize+ - an array of ActiveRecord instances for the model
    # that you are currently importing data into. This synchronizes
    # existing model instances in memory with updates from the import.
于 2013-09-21T19:28:07.523 に答える
0

Y A。first_or_initialize はそのように機能します。first_or_initialize の後に update_attributes を試してください。

Taxline.where(:order_id => order.id).first_or_initialize.update_attributes!( :price => tax_line.price, :rate => tax_line.rate, :title => tax_line.title)

于 2013-09-21T05:17:41.600 に答える