Skip to content
This repository has been archived by the owner on Nov 23, 2021. It is now read-only.

Update instead of create

Ernesto García edited this page Feb 17, 2014 · 2 revisions

By default, the importer will attempt to generate a new model instance per row processed. The importer can be instructed to update records instead, if they already exist, instead of always attempting to generate a new one.

class EmployeeImporter < ActiveImporter::Base
  imports Employee

  fetch_model do
    Employee.where(first_name: row['First name'], last_name: row['Last name']).first_or_initialize
  end

  # ...
end

The code above specifies that, for each row, the importer should attempt to find an existing model for the employee with the first and last name in the row being processed. If this record exist, the row data will be used to update the given model instance. Otherwise, a new employee record will be created.