You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用noticed gem时出现undefined method `notifications_count='错误求助

解决Noticed Gem中undefined method 'notifications_count='错误

错误信息

undefined method `notifications_count=' for #<AppointmentNotifier id: nil, type: "AppointmentNotifier", record_type: "Appointment", record_id: 15, params: {"message"=>"new Message"}, created_at: nil, updated_at: nil>

可能原因及解决方案

1. 通知器的recipient配置错误

检查你的AppointmentNotifier类,确保recipient方法返回的是正确的通知接收者实例(比如User模型对象),而非通知器自身或其他错误对象。错误的recipient会导致Noticed尝试在通知器实例上更新计数,从而触发该错误。

示例正确配置:

class AppointmentNotifier < Noticed::Base
  deliver_by :database

  def recipient
    # 替换为实际的接收者关联,比如预约的所属用户
    record.user
  end
end

2. 接收者模型的计数字段或关联配置问题

如果你的接收者模型(比如User)使用了Noticed的计数缓存功能:

  • 确认模型中正确配置了has_noticed_notifications,并指定了正确的计数字段:
    class User < ApplicationRecord
      # 如果自定义了notifications_count作为计数字段,需显式声明
      has_noticed_notifications counter_cache: :notifications_count
    end
    
  • 检查数据库中接收者表(比如users)是否存在notifications_count整数类型字段,若没有需生成迁移添加:
    rails generate migration AddNotificationsCountToUsers notifications_count:integer default: 0
    rails db:migrate
    

3. 自定义回调或Delivery方法错误调用字段

检查通知器中的自定义回调(比如after_deliver)或自定义Delivery方法,确保没有错误地在通知器实例上调用notifications_count=,应该针对接收者实例操作:

错误写法:

after_deliver do
  self.notifications_count += 1 # 错误:操作的是通知器自身
end

正确写法:

after_deliver do
  recipient.notifications_count += 1
  recipient.save!
end

4. 排查Gem冲突或代码污染

  • 检查是否有其他通知类Gem、ActiveRecord属性修改类Gem与Noticed冲突,尝试临时移除其他可疑Gem后测试。
  • 在控制台手动触发通知,打印接收者信息确认正确性:
    appointment = Appointment.find(15)
    notifier = AppointmentNotifier.new(record: appointment, params: {message: "new Message"})
    puts notifier.recipient.inspect # 确认输出为正确的接收者实例(如User)
    notifier.deliver
    

内容的提问来源于stack exchange,提问作者Neal Holden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:56:10