1

我尝试了https://github.com/rails/actioncable-examples中的动作电缆示例。它与 ActiveRecord 配合得很好。与 NoBrainer 一起用于 rethinkDB 时,我收到ActiveJob::SerializationError (Unsupported argument type: Comment) 。所以我只是通过 id 而不是 self 如下所示的 activejob。但是动作有线服务器无法收听任何频道,并且不会调用 CommentsChannel 方法。

评论.rb

after_save { CommentRelayJob.perform_later(self.id) }

*****comment_relay_job.rb*****
def perform(comment_id)
  comment = Comment.find(comment_id)
  ActionCable.server.broadcast "messages:#{comment.message_id}:comments",
  comment: CommentsController.render(partial: 'comments/comment', locals: { comment: comment }
end

评论频道.rb

module ApplicationCable
  class Channel < ActionCable::Channel::Base; end
end

class CommentsChannel < ApplicationCable::Channel
  def follow(data)
    stop_all_streams
    stream_from "messages:#{data['message_id'].to_i}:comments"
end

  def unfollow
    stop_all_streams
  end
end

评论.咖啡

App.comments = App.cable.subscriptions.create "CommentsChannel",    collection: -> $("[data-channel='comments']")
  connected: ->
    setTimeout =>
       @followCurrentMessage()
       @installPageChangeCallback()
    , 1000

  received: (data) ->
    @collection().append(data.comment) unless @userIsCurrentUser(data.comment)

  userIsCurrentUser: (comment) ->
       $(comment).attr('data-user-id') is $('meta[name=current-user]').attr('id')

  followCurrentMessage: ->
    if messageId = @collection().data('message-id')
      @perform 'follow', message_id: messageId
    else
      @perform 'unfollow'

  installPageChangeCallback: ->
     unless @installedPageChangeCallback
       @installedPageChangeCallback = true
       $(document).on 'page:change', -> App.comments.followCurrentMessage()
4

0 回答 0