使用 Action Cable 从模型 rails 调用 class 方法获取未定义的局部变量或方法

Getting undefined local variable or method using Action Cable calling class method from model, 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
...

据我所知,通过使用控制器和模型,我可以调用 class 方法 after_commit -> {MicropostNotificationsChannel.notify(self)} 然后进入 self.notifiy(notification) 然后 connections_info 是一个实例方法我应该能够在 class 中调用它并执行我的代码,但我在这里得到错误?

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

Channel.rb

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

    def connections_info
      # do stuff here
    end
  end
end

您已将 connections_info 定义为 ApplicationCable::Channel 中的实例方法,但 notify 是 class 方法,因此它正在寻找 [=18] 中的方法=] 级别而不是实例级别。有时 classes 会通过使用 method_missing 来解决这个问题,但乍看之下 Action Cable 似乎并没有做到这一点。在不了解您正在尝试做什么的情况下,很难说是将 connections_info 更改为 class 方法,将 notify 更改为实例方法,还是其他。

当你的redis配置不正确时也会出现这种情况。