parent
392696301c
commit
16133cdd9d
@ -1,7 +1,22 @@
|
|||||||
|
require 'csv'
|
||||||
|
|
||||||
class Recipient < ApplicationRecord
|
class Recipient < ApplicationRecord
|
||||||
belongs_to :school
|
belongs_to :school
|
||||||
validates_associated :school
|
validates_associated :school
|
||||||
|
|
||||||
validates :name, presence: true
|
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
|
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'
|
||||||
@ -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…
Reference in new issue