From beeda191861d11cd9f7ed91a9e9432b544b3cd2d Mon Sep 17 00:00:00 2001 From: Manuel Bustillo Date: Thu, 25 Jul 2024 10:47:49 +0200 Subject: [PATCH] Add feature to import guests from CSV --- app/controllers/guests_controller.rb | 16 ++++++++++++++++ app/views/guests/index.html.erb | 6 ++++++ config/routes.rb | 4 +++- db/seeds.rb | 4 ---- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/app/controllers/guests_controller.rb b/app/controllers/guests_controller.rb index 025f7ef..72baf50 100644 --- a/app/controllers/guests_controller.rb +++ b/app/controllers/guests_controller.rb @@ -1,3 +1,5 @@ +require 'csv' + class GuestsController < ApplicationController before_action :set_guest, only: %i[show edit update destroy] @@ -58,6 +60,20 @@ class GuestsController < ApplicationController end end + def import + csv = CSV.parse(params[:file].read, headers: true) + ActiveRecord::Base.transaction do + csv.each do |row| + guest = Guest.create!(first_name: row['name']) + + guest.affinity_group_list.add(row['affinity_group']) + guest.save! + end + end + + redirect_to guests_url + end + private # Use callbacks to share common setup or constraints between actions. diff --git a/app/views/guests/index.html.erb b/app/views/guests/index.html.erb index 436a01b..d71cfa8 100644 --- a/app/views/guests/index.html.erb +++ b/app/views/guests/index.html.erb @@ -29,3 +29,9 @@ <%= link_to "New guest", new_guest_path %> + +<%= form_with url: import_guests_path, method: :post do |form| %> + <%= form.label :file %> + <%= form.file_field :file %> + <%= form.submit "Import" %> +<% end %> diff --git a/config/routes.rb b/config/routes.rb index fb63987..821cba7 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,7 @@ Rails.application.routes.draw do - resources :guests + resources :guests do + post :import, on: :collection + end resources :expenses # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html diff --git a/db/seeds.rb b/db/seeds.rb index e79ad9b..12a5fa8 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -28,10 +28,6 @@ Expense.create!(name: 'Transportation', amount: 3000, pricing_type: 'fixed') Expense.create!(name: 'Invitations', amount: 200, pricing_type: 'fixed') Expense.create!(name: 'Cake', amount: 500, pricing_type: 'fixed') -<<<<<<< HEAD - -======= ->>>>>>> 8fd0b7c (Modify seeds file to make sure every guest is part of a group) samples = { close_family: 10, family_1_group_a: 5, -- 2.47.1