Search code examples
sqlruby-on-railstagspublic-activity

Rails sql complex query for public_activity


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 =.....

Solution

  • 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!