1

I'm using the public_activity gem with rails 4 to generate an activity feed. The models are as follows:

Class Post 
  has_many :comments
  has_many :taggings
  has_many :tags, through: :taggings 

Class Comment 
  belongs_to :post

Class Tagging
  belongs_to :post
  belongs_to :tag

Class Tag
  has_many :posts, through: :taggings
  has_many :taggings

On the Tags#show action, I'd like to show a feed of all activities of posts and comments belonging to posts belonging to that particular tag. How do I write the query?

class TagsController

    activities = PublicActivity::Activity.order("created_at desc").where('trackable_type =? OR trackable_type = ?', 'Post', 'Comment')
    @activities =.....
Ryan.lay
  • 1,741
  • 2
  • 17
  • 30

1 Answers1

1

SOLUTION.

Ok managed to get it working.

TagsController

def show
    post_ids = @tag.posts.map(&:id)
    comment_ids = Comment.where('post_id IN (?)', post_ids).map(&:id)

    @activities = PublicActivity::Activity.
                  where("(trackable_id IN (?) AND trackable_type = 'Post') 
                  or (trackable_id IN (?) AND trackable_type = 'Comment')", post_ids, comment_ids).
                  order("created_at desc")
    end

It's ugly and unsatisfying but it gets the job done. Bonus points for whoever can optimize this query!

Ryan.lay
  • 1,741
  • 2
  • 17
  • 30
  • Hey..i have almost the same problem with public_activity query. Can you help me? Here is my post: http://stackoverflow.com/questions/31621508/how-to-use-parameters-value-from-public-activity-gem-rails – Ryzal Yusoff Jul 25 '15 at 16:42