Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Observer Not Working

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?

like image 200
goddamnyouryan Avatar asked Nov 27 '22 18:11

goddamnyouryan


1 Answers

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
like image 185
Yannis Avatar answered Dec 05 '22 23:12

Yannis