Search code examples
ruby-on-railsrubyon-duplicate-keyactiverecord-import

Active-record-import on_duplicate_key_update SUM existing value


How is possible to SUM the value of array to my existing row field during on_duplicate_key_update?

For example: Model.import array, on_duplicate_key_update: [ :column_value + array_value]

Thank you.


Solution

  • As mentioned in the README of activerecord-import

    This works on MySQL

    Book.import [book], on_duplicate_key_update: "quantity = quantity + VALUES(quantity)"
    

    Change the format accordingly for PostgreSQL

    Book.import [book], on_duplicate_key_update: {
      conflict_target: [:id], columns: "quantity = books.quantity + excluded.quantity"
    }