我在 ActiveRecord 中有以下問題。
模型和示例欄位
Post [ title:string content:string color:string ]
想象一下,我的模型收到重復發布的帖子,但有時特定帖子帶有“白色”顏色。
現在想象一下,大約 30 分鐘前發布了一個顏色為“白色”的帖子,并且在這 30 分鐘內發布了幾個其他顏色的帖子。
問題是我無法想象如何計算最后一個白色帖子之后出現了多少帖子!
uj5u.com熱心網友回復:
也許是這樣的:
def self.count_post_by_color(color)
where(created_at: Post.where(color: color).last.created_at..Time.current).count
end
uj5u.com熱心網友回復:
def self.count_posts_last_white(last_post_id, last_white_id)
self.where(id: last_white_id..last_result_id - 1).count
end
不久前我問了這個問題,但與我的思想斗爭我最終找到了解決方案
uj5u.com熱心網友回復:
雖然兩種提議的解決方案都可以作業,但它們需要實體化一個Post我認為不必要的物件,相反我們可以像這樣將其設為單個查詢
class Post < ApplicationRecord
scope :posts_since, ->(color) {
where(arel_table[:created_at].gt(
Post.select(arel_table[:created_at].max).where(color: color)))}
end
可呼叫為
Post.posts_since(:white)
結果查詢
SELECT
posts.*
FROM
posts
WHERE
created_at > (SELECT MAX(posts.created_at) FROM posts WHERE posts.color = 'white'))
要“計數”,您只需添加count例如Post.posts_since(:white).count
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/479270.html
