【问题标题】:Using conditionals on callbacks rails在回调轨道上使用条件
【发布时间】:2014-08-15 07:03:11
【问题描述】:

我的评论模型上有一个回调,它创建一个通知,该通知将发送给适当的成员,但如果 current_member 正在评论他自己的可评论对象,我不希望它创建通知。我试过像这样使用除非条件:

after_create :create_notification, on: :create, unless: Proc.new { |commentable| commentable.member == current_member }

def create_notification
    subject = "#{member.user_name}"
    body = "wrote you a <b>Comment</b> <p><i>#{content}</i></p>"
    commentable.member.notify(subject, body, self)
end

但我收到此错误:undefined local variable or method 'current_member' for #&lt;Comment:0x746e008

如何让它按我想要的方式工作?

【问题讨论】:

    标签: ruby-on-rails model callback conditional


    【解决方案1】:

    尝试在模型层使用current_user 或类似的东西是非常不典型的。一个问题是您实际上将模型层与控制器层的当前状态耦合,这将使您的模型的单元测试更加困难和容易出错。

    我建议不要使用after_create 挂钩来执行此操作,而是在控制器层创建通知。这样您就可以访问current_user,而无需费力。

    【讨论】:

    • 哦,好的,感谢您为我指明了正确的方向。我不需要调用 current_member 反正我只是用unless: Proc.new { |comment| comment.member.id == comment.commentable.member.id } 代替
    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2012-05-30
    • 1970-01-01
    相关资源
    最近更新 更多