Rails 观察者不工作

发布于 2024-09-24 00:42:35 字数 581 浏览 5 评论 0原文

我试图在每次保存新的“评论”时在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪之魂 2024-10-01 00:42:35

事实上,只有当注释类无法从观察者名称推断出来时(即不称为 CommentObserver),您才需要 observe :comment

您是否在 application.rb 中声明了您的观察者:

# Activate observers that should always be running
config.active_record.observers = :comment_observer

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:

# Activate observers that should always be running
config.active_record.observers = :comment_observer
下壹個目標 2024-10-01 00:42:35

您不需要 observe 语句,因为您的类名为 CommentObserver。

尝试忽略它。

或者尝试:

observe Comment

代替

observe :comment

You shouldn't need the the observe statement since your class is named CommentObserver.

Try leaving it out.

Or try:

observe Comment

instead of

observe :comment
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文