如何优化对已更改对象及其依赖项记录的搜索
How do I optimize the search for changed object and its dependencies records
我正在搜索自给定日期以来发生更改的活动记录对象。我下面的代码有效,但我想更有效地进行这些调用。有什么想法吗?
# 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)
我正在搜索自给定日期以来发生更改的活动记录对象。我下面的代码有效,但我想更有效地进行这些调用。有什么想法吗?
# 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)