Selaa lähdekoodia

Very unsophisticated mass-Person creation

Maarten van den Berg 7 vuotta sitten
vanhempi
commit
b2cb916cb5

+ 11 - 0
app/controllers/people_controller.rb

@@ -45,6 +45,17 @@ class PeopleController < ApplicationController
45 45
     end
46 46
   end
47 47
 
48
+  def mass_new
49
+  end
50
+
51
+  def mass_create
52
+    require 'csv'
53
+    uploaded_io = params[:spreadsheet]
54
+    result = Person.from_csv(uploaded_io.read)
55
+    flash_message(:success, "#{result.count} people created")
56
+    redirect_to :people
57
+  end
58
+
48 59
   # PATCH/PUT /people/1
49 60
   # PATCH/PUT /people/1.json
50 61
   def update

+ 21 - 0
app/models/person.rb

@@ -68,6 +68,27 @@ class Person < ApplicationRecord
68 68
     self.participants.includes(:activity).where(is_organizer: true)
69 69
   end
70 70
 
71
+  # Create multiple Persons from data found in a csv file, return those.
72
+  def self.from_csv(content)
73
+    reader = CSV.parse(content, {headers: true, skip_blanks: true})
74
+
75
+    result = []
76
+    reader.each do |row|
77
+      p = Person.find_by(email: row['email'])
78
+      if not p
79
+        p = Person.new
80
+        p.first_name  = row['first_name']
81
+        p.infix       = row['infix']
82
+        p.last_name   = row['last_name']
83
+        p.email       = row['email']
84
+        p.birth_date  = Date.strptime(row['birth_date'])
85
+        p.save!
86
+      end
87
+      result << p
88
+    end
89
+
90
+    return result
91
+  end
71 92
   private
72 93
   # Assert that the person's birth date, if any, lies in the past.
73 94
   def birth_date_cannot_be_in_future

+ 6 - 0
app/views/people/mass_new.html.haml

@@ -0,0 +1,6 @@
1
+.container
2
+  .row
3
+    .col-md-12
4
+      = form_tag('/people/mass_new', method: 'post', multipart: true) do
5
+        = file_field_tag 'spreadsheet'
6
+        = submit_tag

+ 2 - 0
config/routes.rb

@@ -21,6 +21,8 @@ Rails.application.routes.draw do
21 21
   get 'logout', to: 'authentication#logout_confirm'
22 22
   delete 'logout', to: 'authentication#logout'
23 23
 
24
+  get 'people/mass_new', to: 'people#mass_new'
25
+  post 'people/mass_new', to: 'people#mass_create'
24 26
   resources :people
25 27
 
26 28
   resources :groups do

+ 1 - 0
public/batch_persons.csv

@@ -0,0 +1 @@
1
+first_name,infix,last_name,birth_date,email,organizers