Rails 观察者不工作
我试图在每次保存新的“评论”时在我的 Rails 应用程序中使用观察者在我的“事件”模型中创建一个新条目。注释保存得很好,但观察者没有正确创建事件。
// comment_observer.rb
class CommentObserver < ActiveRecord::Observer
observe :comment
def after_save(comment)
event = comment.user.events.create
event.kind = "comment"
event.data = { "comment_message" => "#{comment.message}" }
event.save!
end
这个观察器工作得很好,我在控制台中使用它,但它似乎没有正确观察;当我尝试我的应用程序时,它似乎没有创建事件。我没有看到错误或任何东西。
我的environment.rb 文件中还有 config.active_record.observers = :comment_observer
。
我哪里出错了?我应该采取不同的方法吗?
I am trying to use observers in my rails app to create a new entry in my "Events" Model every time a new "Comment" is saved. The comments are saving fine, but the observer is not creating events properly.
// comment_observer.rb
class CommentObserver < ActiveRecord::Observer
observe :comment
def after_save(comment)
event = comment.user.events.create
event.kind = "comment"
event.data = { "comment_message" => "#{comment.message}" }
event.save!
end
This observer works great I use it in the console but it doesn't seem to be observing properly; when I try my app it just doesn't seem to create events. I don't see errors or anything.
Also I have config.active_record.observers = :comment_observer
in my environment.rb file.
Where am I going wrong? Should I be taking a different approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,只有当注释类无法从观察者名称推断出来时(即不称为 CommentObserver),您才需要
observe :comment
。您是否在 application.rb 中声明了您的观察者:
Indeed, you need
observe :comment
only if comment class can’t be inferred from the observer name (i.e., is not called CommentObserver).Did you declare your observer in application.rb:
您不需要 observe 语句,因为您的类名为 CommentObserver。
尝试忽略它。
或者尝试:
代替
You shouldn't need the the observe statement since your class is named CommentObserver.
Try leaving it out.
Or try:
instead of