ActionCable displays blank page after action

I follow the Michael Hartle tutorial on the Rails 5 ActionCable to create a simple chat, and a problem occurs inside my createaction in MessageController:

  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

It works before head :okand then displays a blank HTML page. Magazine:

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

(After that I can refresh the page and the message displays correctly)

Why is this happening?

My RoomChanel class:

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

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

end

My 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
+4
source share
2 answers

Following sugestion, I add as an answer what I did to get around this problem. He does not answer why this is happening, but solves the problem.

Solution: remove head :ok.

-, , , whit assert_response :success , .

0

, , , head :ok, , - .

localhost:3000, , localhost:3030.

, :

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

/config/environments/development.rb

0

Source: https://habr.com/ru/post/1655017/


All Articles