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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With