ruby-on-rails - 如何优化对更改对象及其依赖记录的搜索
问题描述
我正在搜索自给定日期以来已更改的活动记录对象。我下面的代码有效,但我想更有效地进行这些调用。有任何想法吗?
# product_controller.rb file
@products = products.select {|product| product.any_update_since(update_date)}
# product.rb file
def any_update_since(date)
return true if self.updated_since(date) ||
self.specs.any?{|t| t.updated_since(date)} ||
self.content.any?{|t| t.updated_since(date)} ||
self.images.any?{|t| t.updated_since(date)}
return false
end
def updated_since(date)
Time.zone = 'UTC'
update_date = Time.zone.parse(date)
return true if (self.updated_at > update_date)
return true if (self.translations.any?{|t| t.updated_at > update_date})
return false
end
解决方案
如果这些是活动记录关联,您可以完全在数据库层执行此操作:
products
.joins(:specs, :content, :images)
.where('products.updated_at > :date OR specs.updated_at > :date OR contents.updated_at > :date OR images.updated_at > :date', date: update_date)
products
.joins(:translations)
.where('products.updated_at > :date OR translations.updated_at > :date', date: update_date)
推荐阅读
- python - 如何使用 pandas itertuples 比较两个数据帧之间的行?
- pip - pip 和私有存储库
- php - 你如何修复我的多用户登录系统
- python - 在 Python 中编写 Discord 机器人 - 如何让机器人从 subreddit 发送一组随机文本?
- node.js - 如何在浏览器中隐藏 api 请求有效负载?
- matlab - 在 MATLAB2016b 中显示符号方程
- python - tf.test.is_gpu_available() 返回 false
- mysql - Laravel Eloquent 从一组中获取第一行
- python - 我可以重复使用需要用户输入的 docker 容器吗?使用 docker 容器启动时出现 EOF 错误
- c# - 在不同页面上使用 MVVM 链接两个类