首页 > 解决方案 > 使用 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

标签: ruby-on-railsactioncable

解决方案


您已在 中定义connections_info为实例方法ApplicationCable::Channel,但notify它是类方法,因此它在类级别而不是实例级别查找方法。有时课程会通过使用来解决这个问题method_missing,但看起来 Action Cable 并没有一目了然。如果不了解更多有关您要做什么的信息,很难说是更改connections_info为类方法、notify实例方法还是其他方法。


推荐阅读