You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5消息应用需刷新才显示聊天室消息,遇data未定义错误

Fix: "data is not defined" Error in message_me Chatroom

Hey there, let's get this chatroom real-time message display sorted out! The error you're seeing—ReferenceError: data is not defined—is pointing straight to the root of why messages don't show up until you refresh: your frontend CoffeeScript code isn't properly receiving or accessing the data object sent from your Rails Action Cable channel.

Let's Break Down the Problem

That error line in app/assets/javascripts/channels/chatroom.coffee tells us that when your code tries to run $('#message-container').append(data.mod_message), the data variable doesn't exist in that scope. This almost always happens because of a syntax mistake in how you've defined the received callback function for your Action Cable subscription.

Step-by-Step Fixes

1. Correct the received Callback Syntax

CoffeeScript relies heavily on indentation to define code blocks, so it's easy to mess up the structure of your subscription callbacks. Here's what your chatroom.coffee should look like for the received function to properly access data:

App.chatroom = App.cable.subscriptions.create "ChatroomChannel",
  connected: ->
    # Optional: Add any logic that runs when the connection is established
    console.log("Connected to chatroom channel")

  disconnected: ->
    # Optional: Add logic for when the connection drops
    console.log("Disconnected from chatroom channel")

  received: (data) ->
    # This is where we handle incoming messages
    $('#message-container').append(data.mod_message)
    scroll_bottom()

  send_message: (message) ->
    @perform 'send_message', message: message

The key here is that received: (data) -> explicitly declares data as a parameter, and the append and scroll_bottom() calls are indented under this function—so they have access to the data variable.

2. Verify Your Backend Channel is Sending Data Correctly

Make sure your Rails backend is actually sending the mod_message attribute in the broadcast. Check app/channels/chatroom_channel.rb to confirm you have something like this:

class ChatroomChannel < ApplicationCable::Channel
  def subscribed
    chatroom = Chatroom.find(params[:id])
    stream_for chatroom
  end

  def send_message(data)
    message = current_user.messages.create!(content: data['message'], chatroom: Chatroom.find(params[:id]))
    broadcast_message(message)
  end

  private

  def broadcast_message(message)
    broadcast_to chatroom, mod_message: render_message(message)
  end

  def render_message(message)
    ApplicationController.render(partial: 'messages/message', locals: { message: message })
  end
end

The broadcast_to call here sends a mod_message key (matching what your frontend expects) with the rendered message partial. If this key was named differently (like just message), your frontend would try to access data.mod_message which doesn't exist—causing the same error.

3. Double-Check for Typos or Syntax Mistakes

Go back to your original error line: }, $('#message-container').append(data.mod_message), scroll_bottom());
This looks like you might have misplaced commas or brackets, breaking the structure of your subscription object. For example, if you accidentally closed the subscription object before defining the received function, the append call would be outside the function scope where data isn't defined. Fixing the indentation and structure as shown in step 1 should resolve this.

Test It Out

After making these changes, restart your Rails server, clear your browser cache, and send a message. The message should appear in the chatroom immediately without needing a refresh, and that data is not defined error should be gone from your console.

内容的提问来源于stack exchange,提问作者Citizen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:17:45