gpt4 book ai didi

ruby-on-rails - Rails 5 ActionCable 应用程序未定义

转载 作者:行者123 更新时间:2023-12-04 06:07:33 24 4
gpt4 key购买 nike

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

Uncaught ReferenceError: App is not defined at :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

房间 channel .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

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

电缆.js
(function() {
this.App || (this.App = {});

App.cable = ActionCable.createConsumer();

}).call(this);

路由文件
mount ActionCable.server => '/cable'

最佳答案

确保您已添加 require_selfcable.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);

这将添加来自相同 cable.js 的内容文件,如果你定义了 App在其他文件中,那么您需要将其添加到“require”部分。

关于ruby-on-rails - Rails 5 ActionCable 应用程序未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com