Rails Jobs 在 ActionCable 中从哪里调用?如何传递参数?

Where do Rails Jobs get called from in ActionCable and how can you pass parameters?

例如,perform 方法最初是在以下作业中调用的:

jobs/message_broadcast_job.rb

class MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message)
    ActionCable.server.broadcast "room_channel", message: render_message(message) #, roomId: roomId
  end

  private
    def render_message(message)
      ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message })
    end
end

在assets/javascripts/channels/room.coffee中有一个方法调用:

  speak: (message, roomId) ->
    @perform 'speak', message: message, roomId: roomId

但是那个好像调用了channels/room_channel.rb中对应的方法:

def speak(data)
     Message.create! text: data['message'], user_id: 1, room_id: data['roomId']
  end

那么作业是从哪里调用的,我怎样才能将参数传递给它? (具体来说,我有一个房间频道 ID,我已经通过参数传递给 room_channel.rb,但还需要在执行操作中获取它以从相关房间频道广播。

谢谢!

在模型中,models/message.rb

after_create_commit { MessageBroadcastJob.perform_later self }

创建消息后将作业放入队列。因此,在作业文件中,您可以通过对象本身访问参数,在本例中为消息。

具体来说,在本例中为:

 def perform(message)
    ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message) #, roomId: roomId
  end

因为消息的所有属性都可用。