Skip to content

Commit

Permalink
import CSV to rails
Browse files Browse the repository at this point in the history
  • Loading branch information
yshmarov committed Jul 21, 2022
1 parent 253a80d commit 6a6a436
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 2 deletions.
9 changes: 9 additions & 0 deletions app/controllers/users_controller.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
class UsersController < ApplicationController
def import
file = params[:file]
return redirect_to users_path, notice: 'Only CSV please' unless file.content_type == 'text/csv'

CsvImportUsersService.new.call(file)

redirect_to users_path, notice: 'Users imported!'
end

def index
@users = User.all
end
Expand Down
20 changes: 20 additions & 0 deletions app/services/csv_import_users_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class CsvImportUsersService
require 'csv'

def call(file)
file = File.open(file)
csv = CSV.parse(file, headers: true, col_sep: ';')
csv.each do |row|
user_hash = {}
user_hash[:name] = row['First Name']
user_hash[:surname] = row['Last Name']
user_hash[:email] = row['Email Address']
user_hash[:preferences] = row['Favorite Food']
user_hash[:phone] = row['Mobile phone number']
user_hash[:username] = row['Email Address'].split('@').first if row['Email Address'].present?
User.find_or_create_by!(user_hash)
# binding.b
# p row
end
end
end
5 changes: 5 additions & 0 deletions app/views/users/index.html.erb
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
<p style="color: green"><%= notice %></p>

<%= form_with url: import_users_path, method: :post do |form| %>
<%= form.file_field :file, accept: ".csv" %>
<%= form.button "Import" %>
<% end %>

<h1>
Users:
<%= @users.count %>
Expand Down
8 changes: 6 additions & 2 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
Rails.application.routes.draw do
root to: redirect("/users")
resources :users
root to: redirect('/users')
resources :users do
collection do
post :import
end
end
end
5 changes: 5 additions & 0 deletions csv file to import.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
First Name;Last Name;Email Address;Favorite Food;Mobile phone number;;
Yaro;Shm;yaro@example.com;Borsh;;;
Yuli;Zah;yuli@example.com;;573335784;;
Frodo;Baggins;;bread;;;
James;Bond;;guns;;;
Binary file added xls file to import.numbers
Binary file not shown.

0 comments on commit 6a6a436

Please sign in to comment.