`stream_from`和`stream_for`在ActionCable中有什么区别?

23

这里的描述这里似乎暗示了stream_for仅在传入记录时使用,但整个文档非常含糊。有人能解释一下stream_fromstream_for之间的区别,并说明为什么要使用其中之一吗?

3个回答

31

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

to_gid_param 部分的意义是什么?你不能只写成 chat_room_#{params[:chat_room_id]} 吗? - the_critic
它只是将任意字符串编码为有效的非空格字符串吗?还是背后有其他想法? - the_critic
stream_for是用于当我们想要更新特定记录(或记录和关联)时使用的。在底层,Action Cable正在为该记录或该记录及其关联生成唯一的字符串,然后调用stream_from方法。来源:https://www.sitepoint.com/action-cable-and-websockets-an-in-depth-tutorial/ - the_critic
1
gid_param 很难预测。它可以阻止攻击者使用随机 ID 获取流。 - kuboon
@the_critic,如何从客户端订阅一个事先不知道的频道?我的意思是,你如何订阅它? - tommyalvarez
您可以将ID作为连接参数发送。 - Almaron

7

kevinhyunilkim的答案几乎正确,但是前缀取决于频道名称而不是模型类。

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传递简单字符串,它会自动添加通道名称。

0

stream_for 接受一个对象作为参数

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

stream_from 接受一个字符串作为参数

class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_channel_#{params[:id]}"
  end
end

看看这个文章,在我看来它很好地涉及了这个概念。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接