首页 > 解决方案 > 如何优化对更改对象及其依赖记录的搜索

问题描述

我正在搜索自给定日期以来已更改的活动记录对象。我下面的代码有效,但我想更有效地进行这些调用。有任何想法吗?

 # 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

标签: ruby-on-railsrubyactiverecordupdatedate

解决方案


如果这些是活动记录关联,您可以完全在数据库层执行此操作:

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)

推荐阅读