skip to content

In a Rails app, how does a createConsumer subscription's perform call from @rails/actioncable reach a method on an Action Cable channel?

level: middleimportance: should knowfreq 42%

answer

  1. one consumer, one multiplexed socket
  2. default URL: meta tag or /cable
  3. subscriptions.create with channel params
  4. perform adds an action key
  5. public methods only; data has string keys

basics

~10 s

createConsumer() from @rails/actioncable opens one WebSocket (to the action-cable-url meta tag or /cable); consumer.subscriptions.create({channel: "TicketChatChannel", ticket_id: 42}, callbacks) subscribes; subscription.perform("speak", {body}) calls the channel's public speak(data) method.

solid answer

~40 s

`createConsumer()` takes a URL, or reads the `action-cable-url` meta tag that `action_cable_meta_tag` renders, and falls back to `/cable`. One consumer holds one socket, and every subscription is multiplexed over it. `consumer.subscriptions.create({ channel: "TicketChatChannel", ticket_id: 42 }, { connected, disconnected, rejected, received })` sends a `subscribe` command whose JSON identifier becomes the channel's `params`. `subscription.perform("speak", { body: "Hi" })` adds `action: "speak"` to the data and sends a `message` command; the server calls `speak(data)` if `speak` is one of the channel's `action_methods`, its public methods. `data` is a plain Hash with string keys, so read `data["body"]`. `perform` returns only whether the frame was sent; results come back as transmissions or broadcasts to `received`.

code

javascript · 14 lines
javascript
import consumer from "channels/consumer"

const chat = consumer.subscriptions.create(
  { channel: "TicketChatChannel", ticket_id: 42 },
  {
    connected()    { console.log("joined ticket 42") },
    disconnected() { console.log("socket lost") },
    rejected()     { console.log("not your ticket") },
    received(data) { console.log(data.author, data.body) },
    speak(body)    { return this.perform("speak", { body }) }
  }
)

chat.speak("Hello, how can I help?")

go deeper

for a junior

Recall the client calls: createConsumer, subscriptions.create with the channel name, perform for actions, and received for incoming data.

for a middle

Explain how the identifier becomes params, how perform maps to public methods with a string-keyed data hash, and why perform returns no result.

for a senior

Show you keep the action surface small (private helpers), answer with transmit versus broadcast deliberately, and rely on the consumer's reconnect and resubscribe behaviour.

for a principal

Judge when a custom channel with perform calls is worth it compared with plain HTTP requests plus server broadcasts, given testing, authorisation and observability costs.

## The pieces on each side Action Cable's browser library is the npm package `@rails/actioncable`. A **consumer** is the client's connection object; a **subscription** is one channel instance on the server, seen from the browser. The server pieces are a connection (one per socket) and a channel instance (one per subscription). `bin/rails generate channel TicketChat speak` writes: - `app/channels/ticket_chat_channel.rb` with `subscribed`, `unsubscribed` and an empty `speak`; - `app/javascript/channels/consumer.js`, which exports `createConsumer()`; - `app/javascript/channels/ticket_chat_channel.js`, calling `consumer.subscriptions.create("TicketChatChannel", {...})` with a `speak` function that calls `this.perform('speak')`; - with import maps, imports rewritten to `channels/consumer`. ## createConsumer and the URL `createConsumer(url = getConfig("url") || "/cable")` reads `<meta name="action-cable-url">` from the document head. The helper `action_cable_meta_tag` renders that tag from `config.action_cable.url` or `config.action_cable.mount_path`; the generated layout does not include it, so a new app connects to `/cable`, which matches the default mount path. A relative path is turned into a `ws:` or `wss:` URL for the current host. One consumer opens **one** socket. Each `subscriptions.create` adds a subscription to it and sends a `subscribe` command; the socket is shared by all of them. ## Creating a subscription `subscriptions.create(channelOrParams, mixin)` accepts a channel name string or an object: ```javascript const chat = consumer.subscriptions.create( { channel: "TicketChatChannel", ticket_id: 42 }, { connected() { this.perform("join") }, rejected() { showNotAllowed() }, received(data) { appendMessage(data) }, speak(body) { this.perform("speak", { body }) } } ) ``` The main callbacks Rails calls are: | Callback | When | |---|---| | `connected({ reconnected })` | the server confirmed the subscription | | `disconnected({ willAttemptReconnect })` | the socket dropped | | `rejected()` | the channel called `reject` | | `received(data)` | a transmit or broadcast arrived for this subscription | ## From perform to a Ruby method 1. `perform(action, data = {})` sets `data.action = action` and calls `send`, which sends `{command: "message", identifier, data: JSON.stringify(data)}`. It returns `true` if the socket was open and `false` otherwise; it does not wait for the server. 2. The connection's `Subscriptions#execute_command` finds the channel instance by identifier and calls `perform_action` with the decoded data. 3. `extract_action` reads `data["action"]`, defaulting to `receive` when it is missing (which is what `subscription.send(data)` triggers). 4. `processable_action?` checks the name against `action_methods`: the channel's public instance methods, minus `ActionCable::Channel::Base`'s own public methods. A name that is not there is logged as "Unable to process" and ignored. 5. `dispatch_action` calls the method with `data` if it takes one argument, or with none if it takes zero. Exceptions go through `rescue_from` handlers on the channel. ## Practical consequences - **Keep helpers `private`**: every public method on the channel is reachable from any browser. - **`data` has string keys**: it comes from `ActiveSupport::JSON.decode`, a plain Hash, and includes `"action"`. `params`, by contrast, has indifferent access. - **No return values**: to answer the caller, the action calls `transmit(...)`, which reaches only that subscription, or broadcasts to everyone on a stream. - **Reconnects are automatic**: the consumer's connection monitor treats the socket as stale after about two missed 3-second pings and reconnects with backoff, resubscribing every subscription. ## Debugging the round trip When a `perform` seems to do nothing, check the two ends in order: 1. In the browser, `ActionCable.logger.enabled = true` (after `import * as ActionCable from "@rails/actioncable"`) logs subscription confirmations, rejections and received messages. 2. On the server, each dispatched action is logged as `TicketChatChannel#speak({"body" => "Hi"})`, with values filtered through `config.filter_parameters`; an unknown action appears as "Unable to process TicketChatChannel#spek(...)". 3. A subscription that never confirms usually means `subscribed` raised or called `reject`; an action that logs but changes nothing usually means it read `data[:key]` instead of `data["key"]`. ## perform versus a plain HTTP request Not every client-to-server message needs `perform`. Posting a chat message through a form to a controller gives you strong parameters, CSRF protection, validation errors and a normal response, and the controller can then call `TicketChatChannel.broadcast_to` for everyone else. `perform` suits short-lived signals that need no response and no record, such as a typing indicator or presence ping. Messages sent with `perform` carry no authenticity token: the socket was vetted once, by the origin check and `connect`, and each action must do its own authorisation. The usual interview follow-up is about trust: the action name and the data both come from the browser, so every action validates its input and authorises against `current_user` exactly as a controller action would.

  • How does a channel action answer only the browser that called it?
    It calls `transmit(data)`, which sends a frame tagged with that subscription's identifier over its own socket, so only that subscription's `received` sees it. `broadcast_to` and `ActionCable.server.broadcast` go through the pub/sub adapter to every subscriber of the broadcasting instead.
  • What does subscription.send(data) do differently from perform?
    `send` transmits the data without adding an `action` key. On the server `extract_action` then defaults to `receive`, so the channel's `receive(data)` method handles it if it defines one; `perform(name, data)` is simply `send` with `action: name` added.

  • Each consumer.subscriptions.create call opens its own WebSocket.
  • perform can call any method on the channel, including private ones.
  • In a channel action, data[:body] works because data has indifferent access like params.
  • perform waits for the server and returns the Ruby method's return value.
  • createConsumer needs an absolute wss:// URL in every app.