1

我正在使用带有 rails 4 的 public_activity gem 来生成活动提要。型号如下:

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

在 Tags#show 操作中,我想显示属于该特定标签的帖子的所有帖子活动和评论的提要。如何编写查询?

class TagsController

    activities = PublicActivity::Activity.order("created_at desc").where('trackable_type =? OR trackable_type = ?', 'Post', 'Comment')
    @activities =.....
4

1 回答 1

1

解决方案。

好的设法让它工作。

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

这很丑陋且令人不满意,但它可以完成工作。谁可以优化此查询的奖励积分!

于 2014-05-18T18:01:24.790 回答