2014-05-18 41 views
1

我正在使用rails 4的public_activity gem來生成活動提要。該型號如下:public_activity的Rails sql複雜查詢

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 

在標籤#show動作,我想顯示的文章和評論屬於屬於特定標籤的帖子的所有活動的飼料。我如何編寫查詢?

class TagsController 

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

回答

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 

這是醜陋的,不令人滿意的,但它完成了工作。獎勵積分可以優化此查詢的任何人!

+0

嗨..我有幾乎與public_activity查詢相同的問題。你可以幫我嗎?這裏是我的帖子:http://stackoverflow.com/questions/31621508/how-to-use-parameters-value-from-public-activity-gem-rails –