File tree Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change 1
1
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
+
2
17
index do
3
18
id_column
4
19
column :class
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments