Reputation: 5836
I want to be able to display to the user the comments and likes he receives on the content he creates in my rails app, as well as notify him when a another user follows him using the public activity gem.
So far I've made Comment
, Like
and Relationship
include PublicActivity::Common
and I create activities for these objects in my controllers on creation of each of them. My problem comes when retrieving these activities for the current user when they're triggered by activity on his content, so far I have this:
post_ids = "SELECT post_id FROM posts WHERE user_id = :user_id"
comment_ids = Comment.where("post_id IN (#{post_ids})", user_id: current_user.id).map(&:id)
comment_activities = PublicActivity::Activity.order("created_at desc").where(trackable_id: comment_ids , trackable_type: "Comment")
like_ids = Like.where("post_id IN (#{post_ids})", user_id: current_user.id).map(&:id)
like_activities = PublicActivity::Activity.order("created_at desc").where(trackable_id: like_ids , trackable_type: "Like")
relationship_ids = Relationship.where(followed_id: current_user.id).map(&:id)
relationship_activities = PublicActivity::Activity.order("created_at desc").where(trackable_id: relationship_ids, trackable_type: "Relationship")
@activities = comment_activities + like_activities + relationship_activities
But I feel this is a very complicated approach and that I'm probably missing a much simpler way to do it, anyone have any suggestions?
Upvotes: 1
Views: 686
Reputation: 5836
Well the solution for this was staring me in the face the whole time. To solve it I just had to set the recipient
of the activity when creating the activity, like this:
@comment.create_activity :create, owner: current_user, recipient: @post.user
Then to fetch the activity I do the following:
@activities = PublicActivity::Activity.order("created_at desc").where(recipient_id: current_user.id, recipient_type: "User")
And that gives me the actions done on the current user's content.
Upvotes: 1