Rails中用Noticed Gem实现关注通知报错,求问题排查
解决Rails Noticed Gem「关注通知」功能的参数错误问题
错误原因分析
错误信息ArgumentError (wrong number of arguments (given 0, expected 1))指向FollowNotifier的config.params lambda块,结合代码看有两个核心问题:
- Mailer方法参数使用错误:ActionMailer中无法通过
params[:user]获取传递的参数,应该直接使用方法入参。 - Notifier配置的lambda参数不匹配:Noticed调用
config.params的lambda时会传递notification对象,而非直接的recipient,且未声明接收with(record: ...)的参数。
修复步骤
1. 修正FollowNotifier配置
添加param :record声明以接收关联的关系记录,同时调整lambda参数为notification对象:
class FollowNotifier < ApplicationNotifier param :record # 声明接收with传递的record参数 deliver_by :email do |config| config.mailer = "UserMailer" config.method = "new_follow" # 通过notification对象获取收件人和关联记录 config.params = ->(notification) { { user: notification.recipient } } end end
2. 修正UserMailer的new_follow方法
直接使用方法入参user,而非错误的params[:user]:
def new_follow(user) @greeting = "Hi" mail to: user.email end
3. 在follow动作中触发通知
确保用户关注时调用Notifier发送通知(原代码缺少这一步):
def follow relationship = Relationship.create_or_find_by(follower_id: current_user.id, followee_id: @user.id) # 触发关注通知 FollowNotifier.with(record: relationship).deliver(@user) respond_to do |format| format.turbo_stream do render turbo_stream: [ turbo_stream.replace(dom_id_for_follower(@user), partial: "profile/follow_button", locals: { user: @user } ), turbo_stream.update("#{@user.id}-follower-count", partial: "follower_count", locals: { user: @user } ) ] end end end
验证修复
在控制台重新执行命令:
FollowNotifier.with(record: Relationship.first).deliver(User.first)
此时应该能正常发送邮件通知,不再出现参数错误。
内容的提问来源于stack exchange,提问作者ANN17298
相关产品推荐
相关产品推荐

