Alexandre Markiewicz Alexandre Markiewicz - 1 year ago 92
Ruby Question

Rails 5 ActionCable When is a connection is started?

I have discovered ActionCable today and I have created a very simple chat. Now I want to add this into my current project.

When is a connection with a channel established? In my simple chat, I have a controller named Welcome with an index method and a channel named Demo. On the index page, you can write/see messages. I deduce when we access any page of the app, we are automatically connected to the channel? (if i don't add any instructions in connection.rb)

Answer Source

Short answer

When you load the web page.

Long anwser

The client opens the connection to the actioncable channel. According to the docs in the client side section:

When you load the web page (in your case, the welcome controller's index action) javascript such as this will execute:

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

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

  App.cable = ActionCable.createConsumer();

Followed by a subscription function such as:

# app/assets/javascripts/cable/subscriptions/
App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" }

That is what opens the connection to your channel which is defined (as in this example in the server side channels section):

# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  # Called when the consumer has successfully
  # become a subscriber of this channel.
  def subscribed

When the client side javascript subscribes, the connection will eventually lead to the subscribed method of your channel object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download