dfosah
dfosah

Reputation: 23

How do I optimize the search for changed object and its dependencies records

I am searching for active record objects that have changed since a given date. My code below works but I would like to make these calls more effectively. Any ideas?

 # 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

Upvotes: 2

Views: 39

Answers (1)

Jonathan Bennett
Jonathan Bennett

Reputation: 1065

If these are active record associations you can do this entirely at the database layer:

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)

Upvotes: 0

Related Questions