title: Rails ActionCable unsubscribe users when browser close
body: <p>I'm testing ActionCable with a very simple example. 
  I want to see how many users are connected at a time on a website. 
  Users are not registered in the system. 
  Users are assigned a session variable with a uuid.
  To make the example as simple as possible I have not included a model or database.</p>
  
  <pre><code>#app/controller/users_controller.rb
  
  class UsersController &lt; ApplicationController 
  
    def index
      if session[:user].nil?
        session[:user] = SecureRandom.uuid
      end
      @user = session[:user]
      UserBroadcastJob.perform_later @user
      end
    end
  </code></pre>
  
  <p>Views are very simple</p>
  
  <pre><code>#app/views/users/index.html.erb
  
  &lt;h1&gt;Users&lt;/h1&gt;
  
  &lt;div id="users"&gt;
    &lt;%= render "user",user: @user %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Partial for users:</p>
  
  <pre><code>#app/views/users/_user.html.erb
  
  &lt;div class="user"&gt;
    User : &lt;%= user %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I use a job to call socket</p>
  
  <pre><code>#app/jobs/user_broadcast_job.rb
  
  class UserBroadcastJob &lt; ApplicationJob
  queue_as :default
  
    def perform(user)
      ActionCable.server.broadcast 'user_channel', message: render_user(user)
    end
  
    def render_user(user)
      ApplicationController.renderer.render(partial: 'users/user', locals: { user: user })
    end
  end
  </code></pre>
  
  <p>And the channel</p>
  
  <pre><code>App.user = App.cable.subscriptions.create "UserChannel",
  connected: -&gt;
  
  disconnected: -&gt;
  
  received: (data) -&gt;
  console.log(data)
  $("#users").prepend(data.message)
  </code></pre>
  
  <p>This works correctly. In each browser I open the uuid are connected is visible.
  As I do not use database for persistence, the first open browser has all the uuid and the rest of the browsers goes n-1 uuid visible. It's not important.</p>
  
  <p>My question is:</p>
  
  <p>If a browser closes, how can I send a message to delete the uuid from the template?</p>
  
  <p>ActionCable does not work with sessions. </p>
  
  <p>Ruby version:  2.4.0
  Rails version: 5.1.3
  jquery installed via yarn</p>
  
  <p>Thanks!!!!</p>