Importers are classes that you can instruct on how to import data into data models.
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
column 'First name', :first_name
column 'Last name', :last_name
column 'Department', :department do |department_name|
Department.find_by(name: department_name)
end
column 'Salary', :salary, optional: true
on :row_error do |ex|
logger.error("Couldn't import row #{row_index}: #{ex.message}")
end
on :row_processing do
model.owner_id = params[:owner_id]
end
private
def logger
@logger ||= Rails.logger
end
end
Once defined, importers can be invoked to import a given data file.
EmployeeImporter.import('file.xls', params: { owner_id: @user.id })
Documentation
For mote detailed information about the different aspects of importing data with active_importer, refer to the following sections in the wiki.
Getting started
Diving in
- Custom data processing
- Helper methods
- File extension and supported formats
- Passing custom parameters
- Events and callbacks
- Selecting the model instance to import into (Update instead of create)
- Error handling
- Selecting the sheet to get data from
- Skipping rows
Advanced features
Contributing
Contributions are welcome! Take a look at our contributions guide for details.