Use Action Cable to reflect changes in one project occurred due to another project

296 views Asked by At

I am trying to implement Action Cable. I have previously worked with it though only the basics. I am now working on a project where the admin and the client section are two different projects. The database for both is same of-course.

What i want is that as soon as the User (from the Client-Side Project) texts the admin, it should (text) be displayed to the Admin (In the Admin side Project) in real time, i.e without refreshing the page.

How to use ActionCable as API gave me ideas but i'm not sure as how i should move forward with it.

Another idea that i had was to implement action cable in the Admin Project and call it in a action of a controller. Now when the text is created in the client project, i'll call this action (in the controller of admin project; how i have not yet figured out and yet working on it). This way the Action Cable will reflect changes in the Admin.

I don't know if this approach is correct or there's another way.

I'll be grateful for any guidance. Thanks.

P.S: Let me know if this confusing and messy. I'll give it another try.

1

There are 1 answers

0
J. S. On

All you should need is to have the admin user subscribe to a channel only used by admins and at the same time have the messages being submitted by users broadcast to that specific channel.

Something along the lines of this:

channels/admin_chat_channel.rb

class AdminChatChannel < ApplicationCable::Channel
  def subscribed
    if current_user.is_admin?
      stream_from "admin_chat_channel"  
    end
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def update
  end
end

I'm using coffeescript in this example. I can convert it to js if you prefer.

javascripts/channels/admin_chat.coffee

(document).ready ->
  App.merge_requests = App.cable.subscriptions.create {
    channel: "AdminChatChannel"
  },
  connected: ->
    console.log 'Admin Chat Connected'

  disconnected: ->
    console.log 'Admin Chat Disconnected'

  received: (message) ->
    $('.some_chat_div').append(message)

On the controller in which you will be receiving the submitted messages you just need to broadcast the message:

ActionCable.server.broadcast "admin_chat_channel", message