0
ActionCable有問題。我發送消息,但只能在刷新頁面後才能看到。在控制檯我看,這ActionCable工作良好:ActionCable消息在刷新頁面後加載,但在控制檯中都很好
[ActionCable] [[email protected]] ChatsChannel is streaming from chats_1_channel
[ActionCable] [[email protected]] ChatsChannel#send_message({"message"=>"sdasda", "chat_id"=>1})
[ActionCable] [[email protected]] (0.2ms) BEGIN
[ActionCable] [[email protected]] Chat Load (0.3ms) SELECT "chats".* FROM "chats" WHERE "chats"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
[ActionCable] [[email protected]] SQL (1.6ms) INSERT INTO "messages" ("field", "user_id", "chat_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["field", "sdasda"], ["user_id", 1], ["chat_id", 1], ["created_at", 2016-07-27 20:45:45 UTC], ["updated_at", 2016-07-27 20:45:45 UTC]]
[ActionCable] [[email protected]] (17.0ms) COMMIT
[ActionCable] [[email protected]] [ActiveJob] Enqueued MessageBroadcastJob (Job ID: 6273cc4f-3a7a-4349-be41-195e893fe505) to Async(default) with arguments: #<GlobalID:0x007efb9417ea30 @uri=#<URI::GID gid://testchattask/Message/20>>
Message Load (1.3ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = $1 LIMIT $2 [["id", 20], ["LIMIT", 1]]
[ActiveJob] [MessageBroadcastJob] [6273cc4f-3a7a-4349-be41-195e893fe505] Performing MessageBroadcastJob from Async(default) with arguments: #<GlobalID:0x007efbc066c908 @uri=#<URI::GID gid://testchattask/Message/20>>
這裏是chats_channel.rb:
class ChatsChannel < ApplicationCable::Channel
def subscribed
stream_from "chats_#{params['chat_id']}_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def send_message(data)
current_user.messages.create!(field: data['message'], chat_id: data['chat_id'])
end
end
chats.coffee:
jQuery(document).on 'turbolinks:load', ->
messages = $('#messages')
if $('#messages').length > 0
App.room = App.cable.subscriptions.create {
channel: "ChatsChannel"
chat_id: messages.data('chat-id')
},
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
messages.append data['message']
send_message: (message, chat_id) ->
@perform 'send_message', message: message, chat_id: chat_id
$('#new_message').submit (e) ->
$this = $(this)
textarea = $this.find('#message_field')
if $.trim(textarea.val()).length > 1
App.room.send_message textarea.val(), messages.data('chat-id')
textarea.val('')
e.preventDefault()
return false
cable.coffee:
@App ||= {}
App.cable = ActionCable.createConsumer()
我檢查了一切,但沒有找到問題。
一個簡短的總結會幫助審覈(像我一樣)來判斷你的答案的有效性;感興趣的用戶不需要深入代碼來理解你的方法。只需一兩句話就沒問題,工作也不會太多。 –