質問編集履歴
1
情報を追記いたしました
test
CHANGED
@@ -1 +1 @@
|
|
1
|
-
Rails
|
1
|
+
Rails 取得したデータの整形
|
test
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
Rails で質問させてください。
|
2
2
|
|
3
|
-
異なる2つのテーブル(モデル)を union で結合して取得した下記
|
3
|
+
異なる2つのテーブル(モデル)を union で結合して取得した下記取得データの before のようなデータを下記取得データのafterような形に整形して取得することは可能でしょうか?
|
4
4
|
|
5
5
|
|
6
6
|
|
@@ -20,6 +20,88 @@
|
|
20
20
|
|
21
21
|
|
22
22
|
|
23
|
+
##model
|
24
|
+
|
25
|
+
```rb
|
26
|
+
|
27
|
+
class Project < ApplicationRecord
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
|
32
|
+
|
33
|
+
has_many :todos, dependent: :destroy
|
34
|
+
|
35
|
+
accepts_nested_attributes_for :todos, allow_destroy: true
|
36
|
+
|
37
|
+
|
38
|
+
|
39
|
+
has_many :tasks, dependent: :destroy
|
40
|
+
|
41
|
+
accepts_nested_attributes_for :tasks
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
def self.getCombineTodos(project_id)
|
46
|
+
|
47
|
+
sql = <<-EOS
|
48
|
+
|
49
|
+
(select '1' as type_flg, pt.pt_id as id, pt.name as name, pt.period, pt.note, pt.done, pt.order_number, 0 as child_id, 0 as child_name, 0 as child_period, 0 as child_note, 0 as child_done, 0 as child_order_number from (select project_todos.id + 100000000 as pt_id, project_id, period, project_todos.note, done, project_todos.name as name, order_number from project_todos where project_todos.project_id = :project_id) as pt)
|
50
|
+
|
51
|
+
union
|
52
|
+
|
53
|
+
(select '2' as type_flg, pt.id + 200000000, pt.name, pt.period, pt.note, pt.done, pt.order_number, ptt.id as child_id, ptt.name as child_name, ptt.period, ptt.note as chile_note, ptt.done as child_done, ptt.order_number as child_order_number from project_tasks as pt
|
54
|
+
|
55
|
+
left outer join project_task_todos as ptt on pt.id = ptt.project_task_id where pt.project_id = :project_id) ORDER BY order_number ASC
|
56
|
+
|
57
|
+
EOS
|
58
|
+
|
59
|
+
find_by_sql([sql, { project_id: project_id }])
|
60
|
+
|
61
|
+
end
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
end
|
66
|
+
|
67
|
+
```
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
##controller
|
72
|
+
|
73
|
+
上記のmodel内のsqlで取得できるデータを、下記のメソッドで、フロント(Vue)側に渡します。
|
74
|
+
|
75
|
+
```
|
76
|
+
|
77
|
+
# todoとtaskをまとめて同列にして取得
|
78
|
+
|
79
|
+
def combine_todos
|
80
|
+
|
81
|
+
project = Project.getCombineTodos(params[:id])
|
82
|
+
|
83
|
+
|
84
|
+
|
85
|
+
render json: {
|
86
|
+
|
87
|
+
status: 'SUCCESS',
|
88
|
+
|
89
|
+
message: '',
|
90
|
+
|
91
|
+
data: project
|
92
|
+
|
93
|
+
}
|
94
|
+
|
95
|
+
end
|
96
|
+
|
97
|
+
```
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
##取得データ
|
102
|
+
|
103
|
+
|
104
|
+
|
23
105
|
|
24
106
|
|
25
107
|
```before
|
@@ -368,6 +450,12 @@
|
|
368
450
|
|
369
451
|
|
370
452
|
|
453
|
+
|
454
|
+
|
455
|
+
|
456
|
+
|
457
|
+
|
458
|
+
|
371
459
|
####捕捉
|
372
460
|
|
373
461
|
ruby-2.6.2
|