如何编写一个ActiveRecord作用域,该作用域返回最近创建的属于其父级的2条记录



例如,假设我有一个Author类和一个Book类。如何为书籍编写范围,这些书籍是作者最近创建的记录?

我知道最近创作的书籍的范围是

scope :most_recent, -> { order(created_at: :desc).limit(4) }

然而,这会返回任何作者最近创作的书籍。

我在找这样的东西:

author 1: Plato

id | title | created_at 1 | Apology | 23 Jul 2018 2 | Phaedo | 24 Jul 2018 3 | Republic | 25 Jul 2018

author 2: Seneca

id | title | created_at 4 | Oedipus | 3 May 2018 5 | Agamemnon | 4 May 2018 6 | Hercules | 5 May 2018

返回Hercules, Agamemnon, Republic, and Phaedo

ALl以上的答案没有遵循Rails的单一责任约定。把你的范围写在书上是唯一正确的答案!

class Book
scope :most_recent, -> { order(created_at: :desc).limit(4) }
end

查询如下:

# for author with ID=3
Author.find(3).books.most_recent 
scope :most_recent, lambda { |*args|joins(:author).where(books:{:author_id=>args}).order('books.created_on DESC').limit(2) }

在你的图书模型中写下上述范围。要查询任何作者的最新书籍,请致电:

Book.most_recent(author_id)

author_id=要为其获取最新书籍的author/author Model对象的id。

您可以将其添加到Book类中,如下所示:

scope: most_recent_by_author, ->(author_id) { where(author_id: author_id).order(created_at: :desc).limit(2) }

查询:

Book.most_recent_by_author(1)

最新更新