This gem adds an import action in every controller you like to be able to handle csv imports. It includes the complete workflow:
- CSV file upload
- Field mapping with review
- Creating model records
Rails >= 6.0 and Ruby >= 2.7
Install as gem:
gem install csv_mapper
Or in your apps Gemfile
:
gem 'csv_mapper', github: 'tvdeyen/csv_mapper'
# config/routes.rb
resources :myresource do
collection do
get :import
post :import
end
end
# app/controllers/my_resource_controller.b
class MyResourceController
include CSVMapper::ControllerActions
end
# app/controllers/my_resource_controller.b
class MyResourceController
include CSVMapper::ControllerActions
csv_mapper_config(
mapping: {
"Firstname" => :firstname,
"Lastname" => :lastname
}
)
end
See also the implementation in spec/dummy
app!
Nearly any part of the gem can be overridden!
To override the views place a csv_mapper
folder inside your apps app/views
folder.
import.html.erb
=> The import view, where the form is placed onmapper.html.erb
=> The mapper view, where the mapping happensimport_errors.html.erb
=> The import errors view, where import errors while be shown
To override the actions just define the method you want to override inside your controller.
Just have a look into lib/controller_actions.rb
file to see the methods.
This gem is heavily based on Andrew Timberlake's map-fields-gem.
Nevertheless we didn't fork it, because the changes were too fundamental.