bulk import recipients

pull/1/head
Jared Cosulich 9 years ago
parent 392696301c
commit 16133cdd9d

@ -38,6 +38,13 @@ class RecipientsController < ApplicationController
end
end
def import
render and return if request.get?
Recipient.import(params[:file])
redirect_to @school, notice: "Recipients imported."
end
# PATCH/PUT /recipients/1
# PATCH/PUT /recipients/1.json
def update

@ -1,7 +1,22 @@
require 'csv'
class Recipient < ApplicationRecord
belongs_to :school
validates_associated :school
validates :name, presence: true
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
recipient_hash = row.to_hash
recipient = Recipient.where(phone: recipient_hash["phone"])
if recipient.count == 1
recipient.first.update_attributes(recipient_hash)
else
Recipient.create!(recipient_hash)
end
end
end
end

@ -0,0 +1,9 @@
.row
.offset-sm-2.col-sm-8
%h3 Import Recipients To This School
= form_tag import_school_recipients_path(@school), multipart: true do
%br
.form-group
= file_field_tag :file, class: 'form-control-file'
.form-group
= submit_tag "Import", class: 'btn btn-primary'

@ -7,6 +7,8 @@
%p= link_to "Add Recipient", new_school_recipient_path(@school)
%p= link_to "Bulk Add Recipients", import_school_recipients_path(@school)
= link_to 'Edit', edit_school_path(@school)
|

@ -2,7 +2,12 @@ Rails.application.routes.draw do
resources :districts
resources :schools do
resources :recipients
resources :recipients do
collection do
get :import
post :import
end
end
end
devise_for :users

@ -0,0 +1,16 @@
require 'rails_helper'
describe Recipient do
describe "Import" do
let(:data) { "name,phone\rJared,111-222-333\rLauren,222-333-4444\rAbby,333-444-5555\r" }
let(:file) { instance_double('File', path: 'path') }
it "should parse file contents and return a result" do
expect(File).to receive(:open).with('path', universal_newline: false, headers: true) { StringIO.new(data) }
Recipient.import(file)
expect(Recipient.count).to eq(3)
expect(Recipient.all.map(&:name)).to eq(['Jared', 'Lauren', 'Abby'])
end
end
end
Loading…
Cancel
Save