Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently check updated_at and created_at equality on a set of records

Let's say we have 10 records of a Post model, that have the DateTime attributes updated_at and created_at.

I would like to know which of the following three states is correct:

A. All posts are untouched since creation
B. All posts have been updated since creation
C. Some of the posts have been updated and some untouched

What would be the most efficient way of doing this?

like image 894
Fellow Stranger Avatar asked Oct 22 '25 18:10

Fellow Stranger


2 Answers

If you are unable to update the database, you can create several scopes:

scope :changed, where('updated_at > created_at')
scope :unchanged, where('updated_at = created_at')

# Return +true+ if any Posts changed
def self.changed?
  changed.any?
end

# Return +true+ if no Posts changed
def self.unchanged?
  !changed?
end

# Return +true+ if all Posts changed
def self.all_changed?
  unchanged.empty?
end

Note that any?, empty? and many? [source] are optimized such that when merged into a scope, they modify the actual sql by using count(*) vs iterating over all elements in ruby. There are some cases where they may fallback to ruby, but typically you will have a more efficient query.

like image 91
Matt Dressel Avatar answered Oct 25 '25 09:10

Matt Dressel


if you are looking for a speedy solution my suggest is extra flag updated:boolean and after_validate :set_updated_flag action

def set_updated_flag
  update_attribute :updated, true
end

than you can grab it in any way you want, for example with scope

 scope :updated, where(:updated=>true)
like image 32
okliv Avatar answered Oct 25 '25 10:10

okliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!