ActiveRecord models that store activities in Mongo

20 views
Skip to first unread message

Chris Greenwood

unread,
Feb 21, 2018, 1:32:34 AM2/21/18
to Public Activity
Hi, is it possible to track my ActiveRecord (sequel) models but write the activity logs to mongo? Could you point me to any info to help with this? It seems like I can set it up to track documents stored in mongo, but not do both.

Thank you.

Lucas Cantarelli

unread,
Apr 11, 2018, 2:00:28 PM4/11/18
to Public Activity
Hi, Chris.

It's actually possible, but you'll have to implement some workarounds.

First, setup public activity's orm for mongoid just like in the readme.

After that, in the moment that public activity tries to create some activity, you will get an error due to the following code in the mongoid adapter:

trackable.activities.create(options)

In this case, trackable is an AR object and this relation between activities don't exist and won't.

To solve this you'll have to implement the activities method in the models that you track querying the mongodb document like this:

def activities
  PublicActivity::Activity.where(trackable_id: self.id, trackable_type: self.class.to_s)
end

I advise you to put that code in a concern who also includes PublicActivity::Model and tracked method.

At this point, you'll get some error when assigning an owner to an activity due to rails try to find a constant called Owner.
I don't really know why this happens and my time was running out.

To fix this you'll have to add a column to your document like user_id and user_type (the latter is optional if just your users creates activities), or the name you want to replace owner. Then you must set this column like custom fields. There's a example to do that in the wiki.

The last thing you need to do is override the trackable method of an activity because it'll will be querying the sequel in the wrong way (searching for _id columns instead simply id).

I did that in a lib file that I require in my concern above. Something like this:
module PublicActivity
  class Activity
    include ::Mongoid::Attributes::Dynamic

    def user
User.find_by(id: self.user_id)
end

def trackable
self.trackable_type.constantize.find_by(id: self.trackable_id)
end
end
end


Lucas Cantarelli

unread,
Apr 11, 2018, 2:04:41 PM4/11/18
to Public Activity
Unfortunately the last code isn't well indented and i can't edit.

But after these steps you should be ok to run public activity and creating the activities in the mongodb with your app using AR.

Hope that helps.
Reply all
Reply to author
Forward
0 new messages