Fellow Stranger
Fellow Stranger

Reputation: 34013

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?

Upvotes: 4

Views: 2411

Answers (2)

Matt Dressel
Matt Dressel

Reputation: 2194

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.

Upvotes: 2

okliv
okliv

Reputation: 3959

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)

Upvotes: 2

Related Questions