gpt4 book ai didi

ruby-on-rails - 在 Rails 中处理大量查询

转载 作者:行者123 更新时间:2023-11-29 14:35:41 26 4
gpt4 key购买 nike

使用 Rails 和 Postgres 处理大型结果集的最佳方法是什么?直到今天我才遇到问题,但现在我正在尝试返回 @network_hosts 的 124,000 条记录对象,它有效地拒绝了我的开发服务器。

我的 activerecord orm 不是最漂亮的,但我很确定清理它对性能没有帮助。

@network_hosts = []
@host_count = 0
@company.locations.each do |l|
if l.grace_enabled == nil || l.grace_enabled == false
l.network_hosts.each do |h|
@host_count += 1
@network_hosts.push(h)
@network_hosts.sort! { |x,y| x.ip_address <=> y.ip_address }
@network_hosts = @network_hosts.first(5)
end
end
end

最后,我需要能够将 @network_hosts 返回给 Controller ,以便处理到 View 中。

这是 Sidekiq 能够提供帮助的事情,还是会持续这么久?如果要采用 Sidekiq,我该如何处理页面加载时没有 @network_hosts 对象,因为作业正在异步运行?

最佳答案

我相信您想要 (1) 摆脱所有循环(您正在进行大量查询)和 (2) 使用 AR 查询而不是在数组中进行排序。

也许是这样的:

NetworkHost.
where(location: Location.where.not(grace_enabed: true).where(company: @company)).
order(ip_address: :asc).
tap do |network_hosts|
@network_hosts = network_hosts.limit(5)
@host_count = network_hosts.count
end

类似的事情应该在单个数据库查询中完成。

我必须对您的关联是如何设置的以及您正在寻找 grace_enabled 不正确(nil 或 false)的位置做出一些假设。

我还没有测试过这个,所以它很可能是错误的。但是,我认为方向是正确的。

关于ruby-on-rails - 在 Rails 中处理大量查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45069348/

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