gpt4 book ai didi

ruby-on-rails - 每组 Rails LIMIT

转载 作者:行者123 更新时间:2023-11-29 13:05:47 25 4
gpt4 key购买 nike

我试图将每个类别的记录限制为 5,但我最终只返回了 5 条记录。

如何在 Rails ActiveRecord 中翻译这条 sql 语句?

SELECT *
FROM "jobs" a
WHERE (
SELECT COUNT(*)
FROM jobs
WHERE ID = a.ID
) <= 5
AND jobkey_confirmation IS NOT NULL
AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now())

我只能执行以下操作,如上所述只返回 5 条记录:

scope :confirmed_this_month, where("jobkey_confirmation IS NOT NULL AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now())").group("category").limit(5).order("created_at DESC")

最佳答案

可以使用 find_by_sql 吗?

Job.find_by_sql('SELECT * FROM "jobs" a WHERE (SELECT COUNT(*) FROM jobs WHERE ID = a.ID ) <= 5 AND jobkey_confirmation IS NOT NULL AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now()))

或者您希望用 AR Calls 完全取代它?

-- 从评论中提取代码----

def self.limited_grouped_jobs 
find_by_sql("SELECT * FROM jobs a WHERE (SELECT COUNT(*) FROM jobs WHERE ID = a.ID ) <= 5 AND jobkey_confirmation IS NOT NULL AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now())")
end

关于ruby-on-rails - 每组 Rails LIMIT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12957459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com