回答編集履歴

1

配列に格納

2020/06/21 01:16

投稿

yoshi11
yoshi11

スコア2

test CHANGED
@@ -1,14 +1,66 @@
1
1
  ```ruby
2
+
3
+ @user = current_user.id
2
4
 
3
5
  con = ActiveRecord::Base.connection
4
6
 
5
- @result = con.select_all("SELECT DATE_FORMAT(start_time, '%Y-%m-%d') as start_time, SUM(estimated_time), SUM(actual_time) FROM tasks GROUP BY DATE_FORMAT(start_time, '%Y-%m-%d')")
7
+ sql = "SELECT
6
8
 
9
+ DATE_FORMAT(start_time, '%Y-%m-%d') as start_time, SUM(estimated_time), SUM(actual_time)
10
+
11
+ FROM
12
+
13
+ tasks
14
+
15
+ WHERE user_id = #{@user}
16
+
17
+ GROUP BY DATE_FORMAT(start_time, '%Y-%m-%d')"
18
+
7
- @result_hash = @result.to_hash
19
+ @result = con.select_all(sql)
8
20
 
9
21
 
10
22
 
11
- [{"start_time"=>"2020-05-10", "SUM(estimated_time)"=>2.0, "SUM(actual_time)"=>3.0}, {"start_time"=>"2020-05-20", "SUM(estimated_time)"=>2.0, "SUM(actual_time)"=>3.0}, {"start_time"=>"2020-06-08", "SUM(estimated_time)"=>1.0, "SUM(actual_time)"=>1.0}]
23
+ # output
24
+
25
+ [{"start_time"=>"2020-05-10", "SUM(estimated_time)"=>2.0, "SUM(actual_time)"=>3.0}, {"start_time"=>"2020-05-20", "SUM(estimated_time)"=>2.0, "SUM(actual_time)"=>3.0}, {"start_time"=>"2020-06-08", "SUM(estimated_time)"=>1.0, "SUM(actual_time)"=>1.0}
26
+
27
+
28
+
29
+ # Chart.jsで表示するため、viewsで配列に変更
30
+
31
+ <% a = [] %>
32
+
33
+ <% b = [] %>
34
+
35
+ <% c = [] %>
36
+
37
+ <% @result.each do |f| %>
38
+
39
+ <% a.push f['start_time'] %>
40
+
41
+ <% b.push f['SUM(estimated_time)'] %>
42
+
43
+ <% c.push f['SUM(actual_time)'] %>
44
+
45
+ <% end %>
46
+
47
+
48
+
49
+ # output
50
+
51
+ a
52
+
53
+ ["2020-05-10","2020-05-16","2020-05-20","2020-06-05","2020-06-08","2020-06-29"]
54
+
55
+ b
56
+
57
+ [2.0, 2.0, 2.0, 3.0, 1.0, 1.0]
58
+
59
+ c
60
+
61
+ [3.0, 3.0, 3.0, 3.0, 1.0, 1.0]
62
+
63
+
12
64
 
13
65
 
14
66