2016-09-19 43 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