gpt4 book ai didi

ruby-on-rails - 如何在不实际执行的情况下获取由 ActiveRecord#find 创建的 SQL 语句?

转载 作者:行者123 更新时间:2023-12-03 10:34:22 28 4
gpt4 key购买 nike

我正在使用 will_paginate使用一些复杂的查询并且无法正确计算总记录数(以显示适当数量的页面链接) - 即因为按多列分组。

因此,我打算获取用于检索所有记录的 SELECT 查询,而不实际执行它,并用 SELECT COUNT(*) FROM ... 包装它。手动,以获取记录数。

任何想法如何做到这一点?

编辑:我正在使用 Rails 2.3.x

最佳答案

对于 Rails 3:

Rails 3 docs 查看 ActiveRecord::Relation 文档.

# get the relation
rel = User.complex_scope.chained_complex_scope

# get the SQL
# this does not execute the query
sql = rel.to_sql

# find out how many records
# this executes the query behind the scenes
count = rel.size

关于ruby-on-rails - 如何在不实际执行的情况下获取由 ActiveRecord#find 创建的 SQL 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3814738/

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