Search code examples
ruby-on-railsmongoidobservers

Observing a field in rails and mongoid


I have a User model and Following, Follower

User Model

has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following
has_and_belongs_to_many :following, class_name: 'User', inverse_of: :followers

Followers

has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following

Following

has_and_belongs_to_many :followings, class_name: 'User', inverse_of: :followers

And I have a UserObserver which should see if user follower_ids go changed then add it to the user Activities

So how can I watch changes only in follower_ids and get the latest user id to put in the activities


Solution

  • I think that the best option, in this case, is to encapsulate the logic of adding new followers in a method, and, in this method, you can trigger whatever you want:

    #encoding: utf-8
    class User
      include Mongoid::Document
      field :followers, type: Array
      attr_readonly :followers
    
      def add_new_follower(new_follower)
        unless followers.include?(user) 
          followers << user 
          trigger_added_follower_observers(user)
        end
      end
    
      private
      def trigger_added_follower_observers(new_follower)
        # trigger the stuff you want
      end
    end
    

    There are alternative options, like use ruby's Observable module (http://www.ruby-doc.org/stdlib-1.9.3/libdoc/observer/rdoc/Observable.html), MongoID observers (http://mongoid.org/en/mongoid/docs/callbacks.html#observers), or before_save hook, however IMHO i think the above's code is the best option you have, without "hurting" your model.

    Hope it helps.