0

How can I redirect to a path from a n_channel.rb?

I can't use redirect_to or link_to.

What is the best way?

Shakil
  • 1,044
  • 11
  • 17

2 Answers2

2

Your channel serves as a connection, so you actually do that from some other part of your application.

Assuming you've connected everything properly, you can do the following.

In the aforementioned other part of your application, when the time is ripe for redirect:

def async_redirect(path)
  NChannel.broadcast_to(
    user, # or however you identify your subscriber
    head: 302, # redirection code, just to make it clear what you're doing
    path: path # you'll need to use url_helpers, so include them in your file
  )
end

And then on the front

App.cable.subscriptions.create("NChannel", {
  connected: () => {},

  received: (data) => {
    if (data.head == 302 && data.path) {
      window.location.pathname = data.path; # Voila
    }
  }
});
Andrew Rozhenko
  • 416
  • 4
  • 10
  • This helped in the game app we're building where we had to redirect all players to a new page. If you got a host user that would trigger the redirect for other channel subscribers, you may still need to redirect them manually in your controller. – nakakapagpabagabag Feb 21 '22 at 16:50
1

Redirections are not supposed to be done in any model files(n_channel.rb seems model file).

The ideal way is to return your value from model to controller. Then depending on your business needs have redirections from controller.

Ajay
  • 4,199
  • 4
  • 27
  • 47