2017-05-12 45 views
1

我有下面的代碼在我的Rails應用程序發送ActionCable廣播: ActionCable.server.broadcast 'notification_channel', notification: 'Test message'發送ActionCable特定用戶

連接如下所示:

module ApplicationCable 
    class Connection < ActionCable::Connection::Base 

    identified_by :current_user 

    def connect 
     self.current_user = find_verified_user 
    end 

    def session 
     cookies.encrypted[Rails.application.config.session_options[:key]] 
    end 

    protected 

    def find_verified_user 
     User.find_by(id: session['user_id']) 
    end 

    end 
end 

但是,所有用戶登錄到該應用程序將收到它。 identified_by只確保登錄的用戶可以連接到該頻道,但不限制哪些用戶獲得廣播。

有沒有辦法只發送廣播給某個用戶?

我能想到這樣做的唯一途徑是:

ActionCable.server.broadcast 'notification_channel', notification: 'Test message' if current_user = User.find_by(id: 1) 

1是我想要的目標用戶的ID。

回答

4

對於用戶特定通知我覺得有所述簽約是基於當前用戶UserChannel有用:

class UserChannel < ApplicationCable::Channel 
    def subscribed 
    stream_for current_user 
    end 
end 

這樣ActionCable爲每個用戶創建一個單獨的信道,並且可以使用像這樣的基於用戶對象上的命令:

user = User.find(params[:id]) 
UserChannel.broadcast_to(user, { notification: 'Test message' }) 

這種方式可以處理所有用戶特定的廣播。

+0

一個優雅的解決方案。 –