Perf opt - touching journaled w/o callbacks

Initially the journaled was only touched on journal creation to make sure, that
journal updates, that do not update the journaled element itself (like adding a
note) cause a change in updated_(on|at). This has gone a bit overboard, since
simply touching the journaled causes a roundtrip to the db and triggering of all
save callbacks on journaled in all cases.

These changes try to avoid the db roundtrip by only saving when things actually
changed and avoid triggering the callbacks by using update_all instead of save.
pull/3/head
Gregor Schmidt 12 years ago committed by Martin Czuchra
parent 9755b931dd
commit d95a75ec23
  1. 29
      app/models/journal.rb

@ -33,7 +33,7 @@ class Journal < ActiveRecord::Base
belongs_to :user
#attr_protected :user_id
# "touch" the journaled object on creation
after_create :touch_journaled_after_creation
@ -48,8 +48,33 @@ class Journal < ActiveRecord::Base
# logs like the history on issue#show
named_scope "changing", :conditions => ["version > 1"]
raise "This code relies on ActiveRecord 2.3.x internals. ActiveRecord 3.x's
touch should already not trigger the callbacks, as far as I can tell.
So then it should be save to change the following method back to
journaled.touch" if Rails.version >= '3'
def touch_journaled_after_creation
journaled.touch
current_time = created_at
# strip micro seconds since they will not be stored in db anyway
current_time = current_time - (current_time.usec / 1_000_000.00)
attributes = journaled.class.column_names.select { |c| ['updated_at', 'updated_on'].include? c }
changes = {}
# write new timestamp to journaled model without marking it as dirty
attributes.each do |attribute|
next if current_time == journaled[attribute]
changes[attribute] = journaled.write_attribute_without_dirty(attribute, current_time)
end
return if changes.empty?
# saving without triggering callbacks
primary_key = journaled.class.primary_key
journaled.class.update_all(changes, {primary_key => journaled[primary_key]})
end
# In conjunction with the included Comparable module, allows comparison of journal records

Loading…
Cancel
Save