2016-09-19 40 views
4

我下面的邁克爾·哈特爾tutorial Rails的5 ActionCable,構建一個簡單的聊天,和一個問題是,在MessageController發生我create行動中:ActionCable顯示操作後的空白頁

def create 
    message = current_user.messages.build(message_params) 
    if message.save 
     ActionCable.server.broadcast 'room_channel', 
            content: message.content, 
            username: message.user.username 
     head :ok 
    end 
    end 

它去,直到head :ok,然後顯示一個空的HTML頁面。該日誌:

Processing by MessagesController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"h9UsB78aX8mO8Nyn8eZEUuDzAOxL4V7UCMwNuTfwALliMv7OCkcUIeR4/xXIcvPjwq9H1bphjn6G96G+0VYisw==", "message"=>{"content"=>"oi"}, "commit"=>"Send"} 
    User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] 
    Message Load (2.1ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."created_at" DESC LIMIT ? [["LIMIT", 50]] 
    (0.3ms) begin transaction 
    SQL (9.3ms) INSERT INTO "messages" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["content", "oi"], ["user_id", 1], ["created_at", 2016-09-19 02:12:58 UTC], ["updated_at", 2016-09-19 02:12:58 UTC]] 
    (9.1ms) commit transaction 
[ActionCable] Broadcasting to room_channel: {:content=>"oi", :username=>"alice"} 
Completed 200 OK in 69ms (ActiveRecord: 22.0ms) 


RoomChannel transmitting {"content"=>"oi", "username"=>"alice"} (via streamed from room_channel) 
Finished "/cable/" [WebSocket] for 10.0.2.2 at 2016-09-19 02:12:58 +0000 
RoomChannel stopped streaming from room_channel 

(在那之後,我可以刷新頁面,並正確顯示消息)

這是爲什麼發生?

我RoomChanel類:

class RoomChannel < ApplicationCable::Channel 
    def subscribed 
    stream_from "room_channel" 
    end 

    def unsubscribed 
    # Any cleanup needed when channel is unsubscribed 
    end 

end 

我room.coffee

App.room = App.cable.subscriptions.create "RoomChannel", 
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) -> 
    alert data.content 
+0

我完成了教程。 Whel,這並不能回答我發生的「爲什麼」的問題,但是我對於遇到同樣問題的其他人的建議是:移除「head:ok」。實際上它是不必要的,因爲如果我爲測試添加一個測試「assert_response:success」,它就會通過。 – rwehresmann

+0

我建議你添加這個答案,而不是評論,這樣它可以被提升,更明顯,等等。這也適用於我。 –

+0

很高興知道,@EdRuder。答案已添加。 – rwehresmann

回答

0

繼sugestion,我加入的答案我做了什麼來解決這個問題。它不回答爲什麼會發生這種情況,但解決問題。

解決方法是:刪除head :ok

顯然它是不必要的,因爲如果我在測試中添加測試惠特assert_response :success,它會通過。

+0

不幸的是,這給我返回'找不到模板MessagesController#create,渲染頭:no_content'。它不顯示通常的白色屏幕,但它看起來像按鈕沒有做任何事情。如果我刷新,但消息是可見的。 – luissimo

0

我知道答案已被接受,但此解決方案對我無效,無需刪除head :ok,也許它可以幫助某人。

通常在開發環境中,人們正在運行localhost:3000但我運行在不同的端口localhost:3030

而這種情況下,我不得不添加允許的請求發起該端口,像這樣:

config.action_cable.allowed_request_origins = [ 
     'http://localhost:3030' 
    ] 

/config/environments/development.rb