我正在设置ActionCable以处理我的应用程序的消息传递,并且卡在我不理解的undefined method
错误中。
创建消息时,ActionCable广播将委派给后台工作人员:
model.rb
class Message < ApplicationRecord
after_create_commit { MessageBroadcastWorker.perform_async self }
validates :body, presence: true
end
message_broadcast_worker.rb
class MessageBroadcastWorker
include Sidekiq::Worker
def perform(message)
ActionCable.server.broadcast('messages_channel', message: render_message(message))
end
private
def render_message(message)
ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message })
end
end
邮件索引页面呈现对话中的所有邮件:
index.html.erb
<%= render @messages %>
_ message.html.erb:
<% cache message do %>
<div><%= message.body %></div>
<% end %>
但我收到此错误:
2020-03-22T16:41:01.733Z pid=597 tid=owznmnngh class=MessageBroadcastWorker jid=11d9da030dd20e89cd6c774e INFO: start
2020-03-22T16:41:01.808Z pid=597 tid=owznmnngh class=MessageBroadcastWorker jid=11d9da030dd20e89cd6c774e elapsed=0.075 INFO: fail
2020-03-22T16:41:01.808Z pid=597 tid=owznmnngh WARN: {"context":"Job raised exception","job":{"retry":true,"queue":"default","class":"MessageBroadcastWorker","args":["#<Message:0x00007f9f94227d48>"],"jid":"11d9da030dd20e89cd6c774e","created_at":1584844758.799895,"enqueued_at":1584895261.7334359,"error_message":"undefined method `body' for \"#<Message:0x00007f9f94227d48>\":String","error_class":"ActionView::Template::Error","failed_at":1584844758.877783,"retry_count":11,"retried_at":1584877194.326414},"jobstr":"{\"retry\":true,\"queue\":\"default\",\"class\":\"MessageBroadcastWorker\",\"args\":[\"#<Message:0x00007f9f94227d48>\"],\"jid\":\"11d9da030dd20e89cd6c774e\",\"created_at\":1584844758.799895,\"enqueued_at\":1584895261.7334359,\"error_message\":\"undefined method `body' for \\\"#<Message:0x00007f9f94227d48>\\\":String\",\"error_class\":\"ActionView::Template::Error\",\"failed_at\":1584844758.877783,\"retry_count\":11,\"retried_at\":1584877194.326414}"}
2020-03-22T16:41:01.808Z pid=597 tid=owznmnngh WARN: ActionView::Template::Error: undefined method `body' for "#<Message:0x00007f9f94227d48>":String
2020-03-22T16:41:01.808Z pid=597 tid=owznmnngh WARN: /Users/me/code/project/app/views/messages/_message.html.erb:3:in `block in _app_views_messages__message_html_erb__359591413316599227_70291875480180'
[我知道什么是未定义的方法错误是,但是当我将模型中的body
传递给模型的背景工作人员时,为什么无法在message
上调用self
时遇到了麻烦。
将id
传递到Sidekiq,而不是活动记录对象。
MessageBroadcastWorker.perform_async id
https://github.com/mperham/sidekiq/wiki/Best-Practices#1-make-your-job-parameters-small-and-simple