Rails 5 ActionCable 应用程序未定义

jro*_*occ 5 ruby-on-rails ruby-on-rails-5 actioncable

我是 Rails 5 中的 ActionCable 新手。我正在尝试为我的 Rails 应用程序进行聊天。当我尝试通过控制台发送测试消息App.room.speak('Test!')时,但当我收到错误消息时。

未捕获的 ReferenceError:应用程序未在 :1:1 处定义

房间咖啡

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) ->
  # Called when there's incoming data on the websocket for this channel
  $('message').append data

  speak: (message)->
  @perform 'speak', message: message
Run Code Online (Sandbox Code Playgroud)

房间频道.rb

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

   def unsubscribed
      # Any cleanup needed when channel is unsubscribed
   end

   def speak (data)
     Message.new content: data['message'], user: current_user
   end
end
Run Code Online (Sandbox Code Playgroud)

broadcast_message_job.rb

class BroadcastMessageJobJob < ApplicationJob
   queue_as :default

   def perform(meesage)
     ActionCable.server.broadcast 'room_channel', render_message(message)
   end

   private

   def render_message(message)
     ApplicationController.renderer.render message
   end
end
Run Code Online (Sandbox Code Playgroud)

电缆.js

(function() {
   this.App || (this.App = {});

   App.cable = ActionCable.createConsumer();

}).call(this);
Run Code Online (Sandbox Code Playgroud)

路由文件

mount ActionCable.server => '/cable'
Run Code Online (Sandbox Code Playgroud)

Seb*_*lma 3

确保您已在文件require_self中添加cable.js

// app/assets/javascripts/cable.js
//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});
  App.cable = ActionCable.createConsumer();
}).call(this);
Run Code Online (Sandbox Code Playgroud)

这将添加同一cable.js文件中的内容,如果您已App在其他文件中定义了内容,则需要将其添加到“require”部分中。