Search code examples
ruby-on-railsrubycoffeescriptactioncable

Action cable is working instead I push data


I'm currently learning actionable which is fantastic (instead of the errors). And I'm facing a weird problem.

My goal is to build a channel for the groups creation. To permit the user to see new ones without a refresh.

At this point, all is working great. But when I try to display the name of my groups, the actionable is not working anymore. Group are created well, but their not displaying in real time. So I have to refresh the page to see them. Can anyone help me with this problem ??

My code :

Controller(groups):

  def index
    @company = current_user.company
    @groups = @company.groups
  end

Channel(groups):

class GroupsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "groups"
  end

  def speak(data)
    group = Group.create(name: data['group'], company_id: 12)
    html = ApplicationController.render(partial: 'groups/group', local: {
      group: group
    })

    ActionCable.server.broadcast 'groups', group: html
  end 

end

Coffee file (groups):

App.groups = App.cable.subscriptions.create "GroupsChannel",
  connected: ->

    $(document).on 'keypress', '#group_name', (event) =>
      if (event.keyCode == 13)
        @speak(event.target.value)
        $('#group_name').val('')
        $('#MyNewGroup').modal('toggle')

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    $('#groups_area').append(data.group)

  speak: (group) ->
    @perform 'speak', {group: group}

Views(index):

  <div class="container">
    <h1 style="text-align:center; margin-bottom: 30px; margin-top: 10px;">Vos groupes</h1>
    <div id="groups_area">
      <%= render @groups%>
    </div>
  </div>

Views(_group)

        <div class="col-md-3">  
          <div class="panel panel-success">
            <div class="panel-heading">
              <h3 style="margin-top:0; text-align:center">


====================================Problem========================================
                <%= group.name %>

====================================Problem========================================
              </h3>
            </div>

            <div class="panel-body">
              test body
            </div>
          </div>
        </div>

So when I add this line <%= group.name %>, the prepend action is not working anymore.


Solution

  • You seem to have a typo in your channel file. When rendering a partial, you have to use locals, not local. So do the following change:

    html = ApplicationController.render(partial: 'groups/group', local: {
      group: group
    })
    

    Change local to locals:

    html = ApplicationController.render(partial: 'groups/group', locals: {
      group: group
    })