假设我有一个板模型。董事会有许多职位。我只想找到在(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) }