ruby-on-rails - 使用 Action Cable 从模型、rails 调用类方法获取未定义的局部变量或方法
问题描述
使用动作电缆时出现错误,
NameError (undefined local variable or method `connections_info' for MicropostNotificationsChannel:Class):
app/channels/micropost_notifications_channel.rb:12:in `notify'
app/models/notification.rb:8:in `block in <class:Notification>'
app/controllers/likes_controller.rb:11:in `create'
Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
...
据我所知,通过使用控制器和模型,我可以调用类方法after_commit -> {MicropostNotificationsChannel.notify(self)}
,然后调用实例方法self.notifiy(notification)
,然后作为connections_info
实例方法,我应该能够在该类中调用它并执行我的代码,但我在这里得到错误?
class Notification < ApplicationRecord
...
after_commit -> {MicropostNotificationsChannel.notify(self)}
end
动作有线微博通知频道
class MicropostNotificationsChannel < ApplicationCable::Channel
def subscribe
...
end
def unsubscribe
...
end
def self.notifiy(notification)
connection_results = connections_info
puts connection_results.inspect
end
end
频道.rb
module ApplicationCable
class Channel < ActionCable::Channel::Base
def connections_info
# do stuff here
end
end
end
解决方案
您已在 中定义connections_info
为实例方法ApplicationCable::Channel
,但notify
它是类方法,因此它在类级别而不是实例级别查找方法。有时课程会通过使用来解决这个问题method_missing
,但看起来 Action Cable 并没有一目了然。如果不了解更多有关您要做什么的信息,很难说是更改connections_info
为类方法、notify
实例方法还是其他方法。
推荐阅读
- c - 指针和后缀问题
- php - 在 Laravel 关系查询中调用未定义函数
- javascript - 谁能帮我找到替代算法解决方案 - 不使用 sort()?
- url - 是否可以选择知道我的用户 URL 来自何处?
- python - 如何为我的问题创建堆积条形图?
- python - 激活任何 conda 环境后 conda 命令停止工作
- javascript - Wikiitude cordova 插件相机黑屏只显示试用词(Javascript)
- api - 使用 API 密钥获取 API (Twitter API)
- naudio - 如何将 Linear16 PCM wav 转换为与 g711.org 相同质量的 G711 8-bit 8-khz MULAW wav?
- pandas - 悬停工具提示不适用于 Networkx Graph 的散景可视化