【问题标题】:Rails sql complex query for public_activity用于public_activity的Rails sql复杂查询
【发布时间】:2014-05-18 09:35:12
【问题描述】:

我正在使用带有 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 操作中,我想显示属于该特定标签的帖子的帖子和 cmets 的所有活动的提要。如何编写查询?

class TagsController

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

【问题讨论】:

    标签: sql ruby-on-rails tags public-activity


    【解决方案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
    

    它丑陋且令人不满意,但它可以完成工作。谁能优化这个查询,就给谁加分!

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    相关资源
    最近更新 更多