I have a standalone adaptation of your code (see below). I had to make three small changes to make it work as you expected.
To make Observer work at all, you must create it. In my example, I needed to add the lines:
Mongoid.observers = CommentBadgeObserver Mongoid.instantiate_observers
In Rails, you can achieve the same by adding this to config / application.rb (as per docs ):
config.mongoid.observers = :comment_badge_observer
I think that CommentBadge.check_conditions_for has a small logical error, > 1 should be > 0 .
Finally, I changed the User#award method to save the icon, not the user, because the foreign key field in which the relationship is stored is on the side of the icon.
class Comment include Mongoid::Document field :name belongs_to :user end class CommentBadgeObserver < Mongoid::Observer observe :comment def after_create(comment) CommentBadge.check_conditions_for(comment.user) end end class Badge include Mongoid::Document field :title belongs_to :user end class CommentBadge < Badge def self.check_conditions_for(user) if user.comments.size > 0 badge = CommentBadge.create!(:title => "Comment badge") user.award(badge) end end end class User include Mongoid::Document field :first_name has_many :comments has_many :badges def award(badge) self.badges << badge badge.save! end end Factory.define(:user) do |u| u.first_name 'Bob' end Factory.define(:comment) do |c| c.name 'Some comment...' end
Steve
source share