Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have got a working stand-alone adaptation of your code (see below). I had to make three small changes to get it working the way you were expecting.</p> <p>To get the Observer working at all you have to instantiate it. In my example I needed to add the lines:</p> <pre><code>Mongoid.observers = CommentBadgeObserver Mongoid.instantiate_observers </code></pre> <p>In Rails you can achieve the same thing adding this to config/application.rb (according to the <a href="http://mongoid.org/docs/callbacks/observers.html" rel="noreferrer">docs</a>):</p> <pre><code>config.mongoid.observers = :comment_badge_observer </code></pre> <p>I think there is also a small logic error in <code>CommentBadge.check_conditions_for</code>, the <code>&gt; 1</code> should be <code>&gt; 0</code>. </p> <p>Finally I changed the <code>User#award</code> method to save the badge rather than the user, because the 'foreign key' field that stores the relationship is on the badge side.</p> <pre><code>class Comment include Mongoid::Document field :name belongs_to :user end class CommentBadgeObserver &lt; 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 &lt; Badge def self.check_conditions_for(user) if user.comments.size &gt; 0 badge = CommentBadge.create!(:title =&gt; "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 &lt;&lt; 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 # Observers need to be instantiated Mongoid.observers = CommentBadgeObserver Mongoid.instantiate_observers describe CommentBadgeObserver do it 'should create badges' do @user = Factory.build(:user) @comment = Factory(:comment, :user =&gt; @user) @user.badges.count.should == 1 @user.badges[0].title.should == "Comment badge" end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload