Skip to content

Commit 787b7dd

Browse files
authored
[Feature] Import posts from CSV in Admin section (#706)
1 parent 2f1c87f commit 787b7dd

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

app/admin/post.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,19 @@
11
ActiveAdmin.register Post do
2+
action_item :upload_csv, only: :index do
3+
link_to I18n.t("active_admin.users.upload_from_csv"), action: "upload_csv"
4+
end
5+
6+
collection_action :upload_csv do
7+
render "admin/csv/upload_csv"
8+
end
9+
10+
collection_action :import_csv, method: :post do
11+
errors = PostImporter.call(params[:dump][:organization_id], params[:dump][:file])
12+
flash[:error] = errors.join("<br/>").html_safe if errors.present?
13+
14+
redirect_to action: :index
15+
end
16+
217
index do
318
id_column
419
column :class

app/services/post_importer.rb

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Used in the Admin section to import posts
2+
# to a specific organization, from a CSV file.
3+
4+
require "csv"
5+
6+
class PostImporter
7+
Row = Struct.new(
8+
:user_id,
9+
:type,
10+
:title,
11+
:description,
12+
:category_id,
13+
:created_at,
14+
:start_on,
15+
:end_on
16+
) do
17+
def post_from_row
18+
Object.const_get(type).new(
19+
user_id: user_id,
20+
title: title,
21+
description: description,
22+
category_id: category_id,
23+
created_at: created_at,
24+
start_on: start_on,
25+
end_on: end_on
26+
)
27+
end
28+
end
29+
30+
class << self
31+
def call(organization_id, csv_data)
32+
data = csv_data.read
33+
errors = []
34+
35+
CSV.parse(data, headers: false) do |data_row|
36+
row = Row.new(
37+
data_row[0],
38+
data_row[1],
39+
data_row[2],
40+
data_row[3],
41+
data_row[4],
42+
data_row[5],
43+
data_row[6],
44+
data_row[7]
45+
)
46+
process_row(row, organization_id, errors)
47+
end
48+
49+
errors
50+
end
51+
52+
def process_row(row, organization_id, errors)
53+
post = row.post_from_row
54+
post.organization_id = organization_id
55+
return if post.save
56+
57+
errors.push(user_id: row.user_id, title: row.title, errors: post.errors.full_messages)
58+
end
59+
end
60+
end

0 commit comments

Comments
 (0)