teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

5

autoReload.jsのurl指定部分をlocation.hrefに変更

2020/09/23 11:33

投稿

tomoZQ
tomoZQ

スコア14

title CHANGED
@@ -1,1 +1,1 @@
1
- Railsの自動更新機能
1
+ Railsの自動更新機能ができない
body CHANGED
@@ -8,34 +8,23 @@
8
8
  Chat#newにはチャットの一覧表示部分、チャット入力部分があり、このページで非同期通信、自動更新を実装しています。
9
9
  非同期通信での投稿はできています。
10
10
  ### 発生している問題・エラーメッセージ
11
- エラー出ていませんが、2画面立ち上げるとターミナルには、autoReload.jsで設定している7秒ごと
11
+ コンソールにもターミナルにもエラー出ていないように見えが、autoReload.jsのdoneの処理データが入りません。
12
12
  ```
13
- Started GET "/gossips/4/chats/api/chats?id=28" for ::1 at 2020-09-21 15:35:28 +0900
13
+ Started GET "/gossips/4/chats/new?id=56" for ::1 at 2020-09-23 20:17:42 +0900
14
- Processing by Api::ChatsController#new as JSON
14
+ Processing by ChatsController#new as JSON
15
- Parameters: {"id"=>"4"}
15
+ Parameters: {"id"=>"56", "gossip_id"=>"4"}
16
- User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
16
+ User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
17
- Gossip Load (0.5ms) SELECT `gossips`.* FROM `gossips` LIMIT 1
17
+ Gossip Load (0.4ms) SELECT `gossips`.* FROM `gossips` WHERE `gossips`.`id` = 4 LIMIT 1
18
- ↳ app/controllers/api/chats_controller.rb:4:in `new'
18
+ ↳ app/controllers/chats_controller.rb:35:in `set_gossip'
19
- Rendering api/chats/new.json.jbuilder
19
+ Rendering chats/new.html.haml within layouts/application
20
- Chat Load (0.4ms) SELECT `chats`.* FROM `chats` WHERE `chats`.`gossip_id` = 1 AND (id > 4)
20
+ Chat Load (0.6ms) SELECT `chats`.* FROM `chats` WHERE `chats`.`gossip_id` = 4
21
- ↳ app/views/api/chats/new.json.jbuilder:1
21
+ ↳ app/views/chats/new.html.haml:12
22
+ User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
23
+ ↳ app/views/chats/new.html.haml:12
22
- Rendered api/chats/new.json.jbuilder (Duration: 1.8ms | Allocations: 768)
24
+ Rendered chats/new.html.haml within layouts/application (Duration: 17.9ms | Allocations: 10829)
23
- Completed 200 OK in 9ms (Views: 2.1ms | ActiveRecord: 1.5ms | Allocations: 3880)
25
+ Completed 200 OK in 40ms (Views: 33.4ms | ActiveRecord: 1.9ms | Allocations: 34969)
26
+
24
27
  ```
25
- ```
26
- Started GET "/gossips/4/chats/api/chats?id=30" for ::1 at 2020-09-21 15:35:33 +0900
27
- Processing by Api::ChatsController#new as JSON
28
- Parameters: {"id"=>"4"}
29
- User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
30
- Gossip Load (0.4ms) SELECT `gossips`.* FROM `gossips` LIMIT 1
31
- ↳ app/controllers/api/chats_controller.rb:4:in `new'
32
- Rendering api/chats/new.json.jbuilder
33
- Chat Load (0.5ms) SELECT `chats`.* FROM `chats` WHERE `chats`.`gossip_id` = 1 AND (id > 4)
34
- ↳ app/views/api/chats/new.json.jbuilder:1
35
- Rendered api/chats/new.json.jbuilder (Duration: 1.7ms | Allocations: 768)
36
- Completed 200 OK in 9ms (Views: 2.0ms | ActiveRecord: 1.5ms | Allocations: 3874)
37
- ```
38
- が交互に出力されている状態で、チャットの自動更新がされません。
39
28
  ### 該当のソースコード
40
29
 
41
30
  ```ruby
@@ -47,11 +36,11 @@
47
36
  resources :users, only: [:show, :update, :edit]
48
37
  resources :gossips, only: [:new, :create, :index] do
49
38
  resources :chats, only: [:index, :create, :new]
50
- # namespace :api do
39
+ namespace :api do
51
- # resources :chats, only: :new, defaults: { format: 'json' }
40
+ resources :chats, only: :new, defaults: { format: 'json' }
52
- # end
41
+ end
53
42
  end
54
- get "/gossips/:id/chats/api/chats", action: :new, controller: 'api/chats'
43
+
55
44
  resources :movies do
56
45
  resources :comments, only: :create
57
46
  end
@@ -61,12 +50,17 @@
61
50
  ```ruby
62
51
  #chats_controller.rb
63
52
  class Api::ChatsController < ApplicationController
53
+ before_action :set_gossip
54
+
64
55
  def new
56
+ # ルーティングでの設定によりparamsの中にgroup_idというキーでグループのidが入るので、これを元にDBからグループを取得する
65
57
  gossip = Gossip.find(params[:gossip_id])
58
+ # ajaxで送られてくる最後のメッセージのid番号を変数に代入
66
59
  last_chat_id = params[:id].to_i
60
+ # 取得したグループでのメッセージ達から、idがlast_message_idよりも新しい(大きい)メッセージ達のみを取得
67
- @chats = gossip.chats.includes(:user).where("id > ?", last_chat_id)
61
+ @chats = @gossip.chats.includes(:user).where("id > ?", last_chat_id)
68
- chat = Chat.new
69
62
  end
63
+
70
64
  end
71
65
  ```
72
66
  ```haml
@@ -122,7 +116,8 @@
122
116
  function buildHTML(chat){
123
117
  if ( chat.image ) {
124
118
  let html =
119
+ `
125
- `<div class="chat" data-chat-id=${chat.id}>
120
+ <div class="chat" data-chat-id=${chat.id}>
126
121
  <div class="chat__in">
127
122
  <div class="chat__in__left">
128
123
  <div class="chat__in__left__userIcon">
@@ -146,57 +141,69 @@
146
141
  </div>
147
142
  </div>
148
143
  </div>
149
- </div>`
144
+ </div>
145
+ `
150
146
  return html;
151
147
  } else {
152
148
  let html =
149
+ `
153
- `<div class="chat" data-chat-id=${chat.id}>
150
+ <div class="chat" data-chat-id=${chat.id}>
154
- <div class="chat__in">
151
+ <div class="chat__in">
155
- <div class="chat__in__left">
152
+ <div class="chat__in__left">
156
- <div class="chat__in__left__userIcon">
153
+ <div class="chat__in__left__userIcon">
157
- <img src="${chat.user_image_url}">
154
+ <img src="${chat.user_image_url}">
155
+ </div>
158
156
  </div>
157
+ <div class="chat__in__right">
158
+ <div class="chat__in__right__top">
159
+ <div class="chat__in__right__top__userName">
160
+ ${chat.user_name}
159
- </div>
161
+ </div>
160
- <div class="chat__in__right">
161
- <div class="chat__in__right__top">
162
- <div class="chat__in__right__top__userName">
162
+ <div class="chat__in__right__top__createdTime">
163
- ${chat.user_name}
163
+ ${chat.created_at}
164
+ </div>
164
165
  </div>
166
+ <div class="chat__in__right__bottom">
165
- <div class="chat__in__right__top__createdTime">
167
+ <div class="chat__in__right__bottom__content">
166
- ${chat.created_at}
168
+ ${chat.content}
169
+ </div>
167
170
  </div>
168
171
  </div>
169
- <div class="chat__in__right__bottom">
170
- <div class="chat__in__right__bottom__content">
171
- ${chat.content}
172
- </div>
173
- </div>
174
172
  </div>
175
173
  </div>
176
- </div>`
174
+ `
177
175
  return html;
178
176
  };
179
177
  }
180
178
  let reloadChats = function() {
179
+ //カスタムデータ属性を利用し、ブラウザに表示されている最新メッセージのidを取得
181
180
  let last_chat_id = $('.chat:last').data("chat-id") || 0;
182
181
  $.ajax({
182
+ //ルーティングで設定した通り/groups/id番号/api/messagesとなるよう文字列を書く
183
- url: 'api/chats',
183
+ url: location.href,
184
+ //ルーティングで設定した通りhttpメソッドをgetに指定
184
185
  type: 'get',
185
186
  dataType: 'json',
187
+ //dataオプションでリクエストに値を含める
186
188
  data: {id: last_chat_id}
187
189
  })
188
190
  .done(function(chats) {
191
+ // 更新するメッセージがなかった場合は.doneの後の処理が動かないようにする
189
192
  if (chats.length !== 0) {
193
+ //追加するHTMLの入れ物を作る
190
194
  let insertHTML = '';
195
+ //配列messagesの中身一つ一つを取り出し、HTMLに変換したものを入れ物に足し合わせる
191
196
  $.each(chats, function(i, chat) {
192
197
  insertHTML += buildHTML(chat)
193
198
  });
199
+ //メッセージが入ったHTMLに、入れ物ごと追加
194
200
  $('.chat_new__wrapper__chatsIndex').append(insertHTML);
195
201
  $('.chat_new__wrapper__chatsIndex').animate({ scrollTop: $('.chat_new__wrapper__chatsIndex')[0].scrollHeight});
196
202
  }
197
203
  })
198
204
  .fail(function() {
205
+
199
- alert('やビャー');
206
+ console.log('Error');
200
207
  });
201
208
  };
202
209
  setInterval(reloadChats, 7000);
@@ -205,7 +212,6 @@
205
212
  ```ruby
206
213
  #new.json.jbuilder
207
214
  json.array! @chats do |chat|
208
- json.gossip_id chat.gossip.id
209
215
  json.user_name chat.user.name
210
216
  json.created_at chat.created_at.strftime("%Y年%m月%d日 %H時%M分")
211
217
  json.content chat.content
@@ -217,8 +223,8 @@
217
223
  ```
218
224
 
219
225
  ### 試したこと
226
+ autoReload.jsのurl:部分をapi/chatsからlocation.hrefに変更
220
- ルーティング、コントローラー、jsファイル、jbuilder各ID取得部分を見直
227
+ ラーは表示されなくなったがautoReload.jsのfailの処理にか行えない。
221
- 間違って取得している部分は無いように見えました。
222
228
 
223
229
  ### 補足情報(FW/ツールのバージョンなど)
224
230
  Rails 6.0.3.2

4

状況説明文追記

2020/09/23 11:33

投稿

tomoZQ
tomoZQ

スコア14

title CHANGED
File without changes
body CHANGED
@@ -35,7 +35,7 @@
35
35
  Rendered api/chats/new.json.jbuilder (Duration: 1.7ms | Allocations: 768)
36
36
  Completed 200 OK in 9ms (Views: 2.0ms | ActiveRecord: 1.5ms | Allocations: 3874)
37
37
  ```
38
- が交互に出力されている状態で
38
+ が交互に出力されている状態で、チャットの自動更新がされません
39
39
  ### 該当のソースコード
40
40
 
41
41
  ```ruby

3

発生状況追記

2020/09/23 07:15

投稿

tomoZQ
tomoZQ

スコア14

title CHANGED
File without changes
body CHANGED
@@ -8,7 +8,7 @@
8
8
  Chat#newにはチャットの一覧表示部分、チャット入力部分があり、このページで非同期通信、自動更新を実装しています。
9
9
  非同期通信での投稿はできています。
10
10
  ### 発生している問題・エラーメッセージ
11
- エラーは出ていませんが、ターミナルには、autoReload.jsで設定している7秒ごとに
11
+ エラーは出ていませんが、2画面立ち上げるとターミナルには、autoReload.jsで設定している7秒ごとに
12
12
  ```
13
13
  Started GET "/gossips/4/chats/api/chats?id=28" for ::1 at 2020-09-21 15:35:28 +0900
14
14
  Processing by Api::ChatsController#new as JSON

2

エラーが出力されなくなったが、ターミナルの出力がおかしいので出力内容を記述しました。

2020/09/21 06:57

投稿

tomoZQ
tomoZQ

スコア14

title CHANGED
@@ -1,1 +1,1 @@
1
- 404 (Not Found) Railsの自動更新機能 ルーティングエラー?
1
+ Railsの自動更新機能
body CHANGED
@@ -8,20 +8,34 @@
8
8
  Chat#newにはチャットの一覧表示部分、チャット入力部分があり、このページで非同期通信、自動更新を実装しています。
9
9
  非同期通信での投稿はできています。
10
10
  ### 発生している問題・エラーメッセージ
11
- ```
12
- Failed to load resource: the server responded with a status of 404 (Not Found)
11
+ エラーは出ていませんが、ターミナルには、autoReload.jsで設定している7秒ごとに
13
12
  ```
14
-
13
+ Started GET "/gossips/4/chats/api/chats?id=28" for ::1 at 2020-09-21 15:35:28 +0900
14
+ Processing by Api::ChatsController#new as JSON
15
+ Parameters: {"id"=>"4"}
16
+ User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
17
+ Gossip Load (0.5ms) SELECT `gossips`.* FROM `gossips` LIMIT 1
18
+ ↳ app/controllers/api/chats_controller.rb:4:in `new'
19
+ Rendering api/chats/new.json.jbuilder
20
+ Chat Load (0.4ms) SELECT `chats`.* FROM `chats` WHERE `chats`.`gossip_id` = 1 AND (id > 4)
21
+ ↳ app/views/api/chats/new.json.jbuilder:1
22
+ Rendered api/chats/new.json.jbuilder (Duration: 1.8ms | Allocations: 768)
23
+ Completed 200 OK in 9ms (Views: 2.1ms | ActiveRecord: 1.5ms | Allocations: 3880)
15
24
  ```
16
- http://localhost:3000/gossips/3/chats/new/api/chats?id=139
17
- 404 (Not Found)
18
25
  ```
26
+ Started GET "/gossips/4/chats/api/chats?id=30" for ::1 at 2020-09-21 15:35:33 +0900
27
+ Processing by Api::ChatsController#new as JSON
28
+ Parameters: {"id"=>"4"}
29
+ User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
30
+ Gossip Load (0.4ms) SELECT `gossips`.* FROM `gossips` LIMIT 1
31
+ ↳ app/controllers/api/chats_controller.rb:4:in `new'
19
- コンソールに上記2つのエラーが表示されます。
32
+ Rendering api/chats/new.json.jbuilder
33
+ Chat Load (0.5ms) SELECT `chats`.* FROM `chats` WHERE `chats`.`gossip_id` = 1 AND (id > 4)
20
- また、ターミナルには
34
+ ↳ app/views/api/chats/new.json.jbuilder:1
35
+ Rendered api/chats/new.json.jbuilder (Duration: 1.7ms | Allocations: 768)
36
+ Completed 200 OK in 9ms (Views: 2.0ms | ActiveRecord: 1.5ms | Allocations: 3874)
21
37
  ```
22
- ActionController::RoutingError (No route matches [GET] "/gossips/1/chats/api/chats"):
23
- ```
24
- 表示されす。
38
+ 交互に出力されている状態です。
25
39
  ### 該当のソースコード
26
40
 
27
41
  ```ruby
@@ -37,7 +51,7 @@
37
51
  # resources :chats, only: :new, defaults: { format: 'json' }
38
52
  # end
39
53
  end
40
- get "/gossips/:id/chats/new/api/chats", action: :new, controller: 'api/chats'
54
+ get "/gossips/:id/chats/api/chats", action: :new, controller: 'api/chats'
41
55
  resources :movies do
42
56
  resources :comments, only: :create
43
57
  end
@@ -166,7 +180,7 @@
166
180
  let reloadChats = function() {
167
181
  let last_chat_id = $('.chat:last').data("chat-id") || 0;
168
182
  $.ajax({
169
- url: 'new/api/chats',
183
+ url: 'api/chats',
170
184
  type: 'get',
171
185
  dataType: 'json',
172
186
  data: {id: last_chat_id}
@@ -188,10 +202,24 @@
188
202
  setInterval(reloadChats, 7000);
189
203
  });
190
204
  ```
205
+ ```ruby
206
+ #new.json.jbuilder
207
+ json.array! @chats do |chat|
208
+ json.gossip_id chat.gossip.id
209
+ json.user_name chat.user.name
210
+ json.created_at chat.created_at.strftime("%Y年%m月%d日 %H時%M分")
211
+ json.content chat.content
212
+ json.image chat.image_url
213
+ json.user_id chat.user.id
214
+ json.user_image_url chat.user.image_url
215
+ json.id chat.id
216
+ end
217
+ ```
191
218
 
192
219
  ### 試したこと
193
- 最初はroutes.rbのコメントアウト部分でルーティングをしていたがRouting Errorが出たので現在のーティングに変更。変化な
220
+ ルーティング、コントローラーjsファイ、jbuilderの各ID取得部分を見直
194
- autoReload.jsのajax記述部分のurlをapi/chatsからnew/api/chats変更したが変化なし(エラーに表示されるurlが変わるだけ)
221
+ 間違って取得している部分は無いよう見えました。
222
+
195
223
  ### 補足情報(FW/ツールのバージョンなど)
196
224
  Rails 6.0.3.2
197
225
  ここにより詳細な情報を記載してください。

1

ターミナルのエラー文を追加

2020/09/21 06:43

投稿

tomoZQ
tomoZQ

スコア14

title CHANGED
File without changes
body CHANGED
@@ -17,7 +17,11 @@
17
17
  404 (Not Found)
18
18
  ```
19
19
  コンソールに上記2つのエラーが表示されます。
20
-
20
+ また、ターミナルには
21
+ ```
22
+ ActionController::RoutingError (No route matches [GET] "/gossips/1/chats/api/chats"):
23
+ ```
24
+ が表示されます。
21
25
  ### 該当のソースコード
22
26
 
23
27
  ```ruby