From 8734de2c695dc7b997eef0a92202a21d6549cb97 Mon Sep 17 00:00:00 2001 From: jzmalik123 Date: Sun, 2 Feb 2025 19:55:01 +0500 Subject: [PATCH] refactor import blogs action --- app/controllers/blogs_controller.rb | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/app/controllers/blogs_controller.rb b/app/controllers/blogs_controller.rb index 9e0888a..f52db50 100644 --- a/app/controllers/blogs_controller.rb +++ b/app/controllers/blogs_controller.rb @@ -64,15 +64,20 @@ def destroy def import file = params[:attachment] data = CSV.parse(file.to_io, headers: true, encoding: 'utf8') - # Start code to handle CSV data - ActiveRecord::Base.transaction do - data.each do |row| - current_user.blogs.create!(row.to_h) - end + + # Prepare data for bulk insert + blogs = data.map do |row| + hash = row.to_h + hash["user_id"] = current_user.id + hash end - # End code to handle CSV data - redirect_to blogs_path + + # Perform bulk insert + Blog.insert_all(blogs) + + redirect_to blogs_path, notice: "#{blogs.size} blogs were successfully imported." end + private # Use callbacks to share common setup or constraints between actions.