1

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?

8vius
  • 5,786
  • 14
  • 74
  • 136
  • Do you have associations on the user model (eg `user :has_many :comments`) ? if so, why not just do `current_user.comments` instead of the `Comment.where...` (and the same for other associations). That's what associations are for :) – Taryn East Jul 08 '14 at 01:03
  • Also - once you've got that working, I'd google "polymorphic associations" – Taryn East Jul 08 '14 at 01:04
  • Yes, I do have those associations set up. But I need the comment ids on the posts of the current user, not sure how to turn that into a current_user.posts.comments type of deal, I feel I'd end up with something similar to what I have now. And the activity is already polymorphic in the gem. The thing is compounding it all into one stream and there's different kinds of activities. – 8vius Jul 08 '14 at 16:17
  • ah... in which case you want `has_many :comments, through: :posts` – Taryn East Jul 08 '14 at 23:16

1 Answers1

1

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.

8vius
  • 5,786
  • 14
  • 74
  • 136