根据子范围过滤父模型

时间:2019-06-17 18:49:42

标签: sql ruby-on-rails postgresql activerecord

借助此post,我能够创建一个范围来过滤趋势板。我现在正在寻找在董事会父模型上创建范围的方法。因此,我希望让所有拥有热门董事会的父母代替退回董事会。不幸的是我遇到了这个错误:

ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR:  subquery has too many columns)

这是我设置范围的方式:

scope :trending, -> { where(board: Board.trending) }

以下是关系的完整摘要:

class Album < ApplicationRecord
  has_one :board, as: :boardable

  scope :trending, -> { where(board: Board.trending) }
end

class Artist < ApplicationRecord
  has_one :board, as: :boardable

  scope :trending, -> { where(board: Board.trending) }
end

class Board < ApplicationRecord
  belongs_to :boardable, polymorphic: true, optional: true

  scope :trending, -> {
    joins(:posts)
     .select("boards.*, count(posts.id) as latest_posts_count")
     .where('posts.created_at >= ?', 7.days.ago)
     .where(board_category_id: nil)
     .order('latest_posts_count desc')
     .group('boards.id')
     .limit(10)
  }
end

0 个答案:

没有答案