【发布时间】:2016-12-24 10:29:33
【问题描述】:
here 的描述似乎暗示 stream_for 仅在传入记录时使用,但总体而言,文档相当模糊。谁能解释stream_from 和stream_for 之间的区别以及为什么要使用一个而不是另一个?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5 actioncable
here 的描述似乎暗示 stream_for 仅在传入记录时使用,但总体而言,文档相当模糊。谁能解释stream_from 和stream_for 之间的区别以及为什么要使用一个而不是另一个?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5 actioncable
stream_for 只是stream_from 的简单包装方法。
当您需要与特定模型相关的流时,stream_for 会自动为您从模型和频道生成广播。
假设您有一个 chat_room 类的 ChatRoom 实例,
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]} 吗?
stream_for is used when there is a particular record (or record and association) we want updates about. Under the hood, Action Cable is generating a unique string for that record or that record and its association and then calls the stream_for [sic -- probably should be 'stream_from'] method.Source: sitepoint.com/action-cable-and-websockets-an-in-depth-tutorial
kevinhyunilkim's answer 几乎没问题,但前缀取决于通道名称,而不是模型类。
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,它只是添加频道名称。
【讨论】:
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
查看article,我认为它很好地处理了这个概念
【讨论】: