4

每次保存新的“评论”时,我都试图在我的 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

这个观察者工作得很好,我在控制台中使用它,但它似乎没有正确观察;当我尝试我的应用程序时,它似乎并没有创建事件。我没有看到错误或任何东西。

config.active_record.observers = :comment_observer的 environment.rb 文件中也有。

我哪里错了?我应该采取不同的方法吗?

4

2 回答 2

25

实际上,observe :comment只有在无法从观察者名称推断出评论类(即,不称为 CommentObserver)时才需要。

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

# Activate observers that should always be running
config.active_record.observers = :comment_observer
于 2010-09-19T06:57:55.160 回答
2

由于您的类被命名为 CommentObserver ,因此您不应该需要观察语句。

试着把它排除在外。

或尝试:

observe Comment

代替

observe :comment
于 2010-09-19T03:10:54.317 回答