代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

基于post-count和frequency的趋势分析算法

  •  0
  • Carl Edwards monkbroc  · 技术社区  · 5 年前

    假设我有一个板模型。董事会有许多职位。我只想找到在(x)天内拥有最高职位数的董事会。下面是我非常天真的做法。如果我得到了错误代码:

    ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "posts")
    LINE 1: SELECT  "boards".* FROM "boards" WHERE (board.posts.created_...
                                                    ^
    : SELECT  "boards".* FROM "boards" WHERE (board.posts.created_at >= '2019-06-05 12:14:30.661233') LIMIT $1
    

    请让我知道,除了我收到的错误之外,还有没有更好的方法可以做到这一点。

    class Board < ApplicationRecord
      has_many :posts
    
      scope :trending, -> { includes(:posts).where('board.posts.created_at >= ?', Time.now-7.days).order(posts_count: :desc) }
    end
    
    class Post < ApplicationRecord
      belongs_to :board, counter_cache: true
    end
    

    更新: 所以我设法想出了一个工作范围,但不能百分之百确定它是否是最理想的。您的想法将不胜感激:

    scope :trending, -> { includes(:posts).where(posts: { created_at: Time.now - 7.days }).order(posts_count: :desc) }
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Deepak Mahakale    5 年前

    更新:

    Board.joins(:posts)
         .select("boards.*, count(posts.id) as latest_posts_count")
         .where('posts.created_at >= ?', 7.days.ago)
         .order('latest_posts_count desc')
         .group('boards.id')
    

    试试这个,你需要加入它并按 board_id

    Board.joins(:posts)
         .select("boards.*, count(posts.id) as posts_count")
         .where('posts.created_at >= ?', 7.days.ago)
         .order('posts_count desc')
         .group('boards.id')
    

    说明:

    • 我们加入了(内部加入)表,因此默认情况下,只有至少一个post与之关联的board
    • 我们是根据邮递数量订购的
    • 我们根据boards.id对它们进行分组