|
1 | 1 | class UpdateFixTermItemRelation < ActiveRecord::Migration[7.0] |
2 | 2 | def up |
| 3 | + after_1999_id = select_value("SELECT id FROM terms WHERE value = 'After 1999'") |
| 4 | + after_2000_id = select_value("SELECT id FROM terms WHERE value = 'After 2020'") |
| 5 | + return unless after_1999_id && after_2000_id |
| 6 | + |
3 | 7 | execute <<~SQL.squish |
4 | | - old_id = select_value("SELECT id FROM terms WHERE value = 'After 1999'") |
5 | | - new_id = select_value("SELECT id FROM terms WHERE value = 'After 2020'") |
6 | | - return unless old_id && new_id |
7 | | -
|
8 | 8 | WITH target AS ( |
9 | 9 | SELECT it.term_id, it.item_id |
10 | 10 | FROM items i |
11 | 11 | JOIN items_terms it ON i.id = it.item_id |
12 | 12 | JOIN terms t ON it.term_id = t.id |
13 | | - WHERE t.id = #{old_id} |
| 13 | + WHERE t.id = #{after_1999_id} |
14 | 14 | AND i.date = '[2020]' |
15 | 15 | ) |
16 | 16 | UPDATE items_terms it |
17 | | - SET term_id = #{new_id} |
| 17 | + SET term_id = #{after_2000_id} |
18 | 18 | FROM target |
19 | 19 | WHERE it.item_id = target.item_id |
20 | 20 | AND it.term_id = target.term_id; |
21 | 21 | SQL |
22 | 22 | end |
23 | 23 |
|
24 | | - def up |
25 | | - new_id = select_value("SELECT id FROM terms WHERE value = 'After 1999'") |
26 | | - old_id = select_value("SELECT id FROM terms WHERE value = 'After 2020'") |
27 | | - return unless old_id && new_id |
| 24 | + def down |
| 25 | + after_1999_id = select_value("SELECT id FROM terms WHERE value = 'After 1999'") |
| 26 | + after_2000_id = select_value("SELECT id FROM terms WHERE value = 'After 2020'") |
| 27 | + return unless after_1999_id && after_2000_id |
28 | 28 |
|
29 | 29 | execute <<~SQL.squish |
30 | 30 | WITH target AS ( |
31 | 31 | SELECT it.term_id, it.item_id |
32 | 32 | FROM items i |
33 | 33 | JOIN items_terms it ON i.id = it.item_id |
34 | 34 | JOIN terms t ON it.term_id = t.id |
35 | | - WHERE t.id = #{old_id} |
| 35 | + WHERE t.id = #{after_2000_id} |
36 | 36 | AND i.date = '[2020]' |
37 | 37 | ) |
38 | 38 | UPDATE items_terms it |
39 | | - SET term_id = #{new_id} |
| 39 | + SET term_id = #{after_1999_id} |
40 | 40 | FROM target |
41 | 41 | WHERE it.item_id = target.item_id |
42 | 42 | AND it.term_id = target.term_id; |
|
0 commit comments