这里的描述这里似乎暗示了stream_for
仅在传入记录时使用,但整个文档非常含糊。有人能解释一下stream_from
和stream_for
之间的区别,并说明为什么要使用其中之一吗?
这里的描述这里似乎暗示了stream_for
仅在传入记录时使用,但整个文档非常含糊。有人能解释一下stream_from
和stream_for
之间的区别,并说明为什么要使用其中之一吗?
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.rbkevinhyunilkim的答案几乎正确,但是前缀取决于频道名称而不是模型类。
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
看看这个文章,在我看来它很好地涉及了这个概念。
to_gid_param
部分的意义是什么?你不能只写成chat_room_#{params[:chat_room_id]}
吗? - the_critic