Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions app/controllers/blogs_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down