Good day! There is a problem with the websocket in Rails, unfortunately, I still haven't figured out how to implement the functionality using ActionCable, so I used private_pub.

Everything works, but if you follow the links and return to the page where you subscribe to the channel with the help of the subscribe_to helper, the callback is executed several times (+ for each turbolinks download).

I think that this is not the fault of the kolbek, since If you send js to the channel, the picture is the same. It seems to me that every time the page loads, the channel is subscribed to this behavior from here.

How to win, not to think ... Write in the comments, what code to publish, thank you!

    1 answer 1

    This behavior is caused by the fact that every time a page is rendered with turbolinks, where a subscription to the ws channel occurs, a new subscription is created and the last one remains working, respectively, when the server fills a message on the page, several scripts are executed for each subscription. Found 3 solutions to the problem:

    1. Use ActionCable instead of PrivatePub
    2. Leave PrivatePub , but remove turbolinks
    3. Each time you load the page, first unsubscribe from the channel, and then subscribe again. In js you need to add the following lines:

      PrivatePub.unsubscribeAll ();

      PrivatePub.subscribe (channel, function (data, channel) {

      });

    But there is no unsubscribeAll function in the release, but there is a repository master. It looks like this gem is no longer supported, the last release was August 20, 2014, and the last functional change in the wizard was August 22, 2014 and there were no more releases. Therefore, if we want to leave PrivatePub и Turbolinks , then in Gemfile we need to add the following line:

     gem 'private_pub', git: 'git@github.com:ryanb/private_pub.git' 

    But I vote for the first option, because It works out of the box.

    • one
      In the last version, you can write this: gem 'private_pub', github: 'ryanb/private_pub - will also work - Vitaly Emelyantsev