2016-08-17 68 views

回答

7

stream_for只是一個簡單的包裝方法stream_from

當你需要的是關係到一個特定模型的流,stream_for自動模式和渠道爲您生成廣播。

讓我們假設你有ChatRoom類的實例chat_room

stream_from "chat_rooms:#{chat_room.to_gid_param}" 

stream_for chat_room # equivalent with stream_from "chat_rooms:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE" 

的兩行代碼做同樣的事情。

https://github.com/rails/rails/blob/master/actioncable/lib/action_cable/channel/streams.rb

+0

'to_gid_param'部分的要點是什麼?你不能只說'chat_room _#{params [:chat_room_id]}'嗎? –

+0

難道僅僅用於編碼任意字符串成一個有效的非空白字符串?或者有沒有其他想法背後呢?當有一個特定的記錄(或記錄和關聯),我們希望有關更新 –

+0

'stream_for使用。引擎蓋下,作用電纜被用於生成該記錄或記錄和公司章程的唯一字符串,然後調用stream_for [原文如此 - 也許應該是「stream_from」] method.'Source:https://www.sitepoint.com /動作電纜和 - 的WebSockets-的縱深教程/ –

0

kevinhyunilkim's answer 幾乎是好的,但前綴取決於CHANNEL_NAME,而不是模型類。

class CommentsChannel < ApplicationCable::Channel 
    def subscribed 
    stream_for article 
    # is equivalent to 
    stream_from "#{self.channel_name}:{article.to_gid_param}" 
    # in this class this means 
    stream_from "comments:{article.to_gid_param}" 
    end 

    private 

    # any activerecord instance has 'to_gid_param' 
    def article 
    Article.find_by(id: params[:article_id]) 
    end 
end 

,你也可以通過簡單的字符串stream_for這只是增加了頻道名稱。