Commit d40df13
committed
Add batch_transaction to make transaction work on model validation*
This is the core part when importing from csv.
```ruby
def batch_import
@resource.transaction do
run_callback(:before_batch_import)
batch_result = resource.import(headers.values, csv_lines, import_options)
run_callback(:after_batch_import)
batch_result
end
end
```
What confusing me is that the transaction won't rollback, when some records fail on validation. It means that now the csv file is partially imported, and I need to modify the failed records and delete the succeed records to import again, which seems weird to me.
The transaction relies on the `import` method defined by *activerecord-import*. The `import` method does the validation and saves the result to `failed_instances`, which will never raise an exception on validation. Check the code for details https://github.com/zdennis/activerecord-import/blob/6c06b3ceb53f83e1ce930eab35cdd4b6375c57ca/lib/activerecord-import/import.rb#L340-L365
So I made this update to manually trigger a rollback:
```ruby
raise ActiveRecord::Rollback if import_options[:batch_transaction] &&
batch_result.failed_instances.any?
```
P.S.
The validation I'm talking about is on model level, not on DB
level. The `import` method will raise the DB level exception to tirgger
the rollback, like add a record with a duiplicate field which has a uniq index.1 parent ca7d286 commit d40df13
File tree
4 files changed
+13
-6
lines changed- lib/active_admin_import
4 files changed
+13
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
65 | 65 | | |
66 | 66 | | |
67 | 67 | | |
| 68 | + | |
68 | 69 | | |
69 | 70 | | |
70 | 71 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
8 | 8 | | |
9 | 9 | | |
10 | 10 | | |
| 11 | + | |
11 | 12 | | |
12 | 13 | | |
13 | 14 | | |
| |||
31 | 32 | | |
32 | 33 | | |
33 | 34 | | |
34 | | - | |
35 | | - | |
36 | | - | |
37 | 35 | | |
38 | 36 | | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
39 | 41 | | |
40 | 42 | | |
41 | 43 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
16 | 16 | | |
17 | 17 | | |
18 | 18 | | |
| 19 | + | |
19 | 20 | | |
20 | 21 | | |
21 | 22 | | |
| |||
47 | 48 | | |
48 | 49 | | |
49 | 50 | | |
50 | | - | |
| 51 | + | |
51 | 52 | | |
52 | 53 | | |
53 | 54 | | |
| |||
97 | 98 | | |
98 | 99 | | |
99 | 100 | | |
| 101 | + | |
100 | 102 | | |
101 | 103 | | |
102 | 104 | | |
| 105 | + | |
103 | 106 | | |
104 | | - | |
105 | 107 | | |
| 108 | + | |
106 | 109 | | |
107 | 110 | | |
108 | 111 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
6 | 6 | | |
7 | 7 | | |
8 | 8 | | |
| 9 | + | |
9 | 10 | | |
10 | 11 | | |
11 | 12 | | |
| |||
40 | 41 | | |
41 | 42 | | |
42 | 43 | | |
43 | | - | |
| 44 | + | |
0 commit comments