title: How do I get the ID of a model instance into an Action Cable channel param hash?
body: <p>The <a href="https://edgeguides.rubyonrails.org/action_cable_overview.html" rel="nofollow noreferrer">Rails Action Cable overview</a> states the following:</p>
  
  <blockquote>
    <p>If you have a stream that is related to a model, then the broadcasting
    used can be generated from the model and channel. The following
    example would subscribe to a broadcasting like
    <code>comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE</code></p>
  </blockquote>
  
  <pre><code>class CommentsChannel &lt; ApplicationCable::Channel
    def subscribed
      post = Post.find(params[:id]).   # This is the line I'm trying to copy.
      stream_for post
    end
  end
  </code></pre>
  
  <p>This is <em>exactly</em> what I want to do for one of my models (I have a model <code>Incident</code> that has many <code>Messages</code>, therefore I am making a <code>MessagesChannel</code>). However, I don't understand how the <code>:id</code> param was passed in this scenario. I know that the first argument of the <code>App.cable.subscriptions.create</code> call in the client-side CoffeeScript is passed to the server-side code as the params hash, but since the CoffeeScript is called on every page of the application, how do I know whether I am looking at an Incident page (because the ID could refer to another model if we're on a different page, or not be present at all), and how do I get the Incident ID into the channel params?</p>
  
  <p>My (incorrect) attempt was this:</p>
  
  <pre><code>App.messages = App.cable.subscriptions.create { channel: "MessagesChannel", id: &lt;%= params[:id] %&gt; },
      connected: -&gt;
          # ...
      # ...
  </code></pre>
  
  <p>And if I'm doing this wrong altogether, feel free to let me know the correct way.</p>