with this fix touch method - does not call validations - doest not call callbacks - updates updated_at/on along with attribute if attribute is provided - marks udpated_at/on and attribute as NOT changed

[#2520 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
This commit is contained in:
Neeraj Singh
2010-07-09 14:11:51 -04:00
committed by José Valim
parent 2aed63eb52
commit 1d45ea0814
3 changed files with 18 additions and 9 deletions

View File

@@ -111,6 +111,7 @@ module ActiveRecord
if record_update_timestamps
timestamp_attributes_for_update_in_model.each do |column|
hash[column] = read_attribute(column)
@changed_attributes.delete(column.to_s)
end
end

View File

@@ -21,24 +21,22 @@ module ActiveRecord
end
# Saves the record with the updated_at/on attributes set to the current time.
# If the save fails because of validation errors, an
# ActiveRecord::RecordInvalid exception is raised. If an attribute name is passed,
# that attribute is used for the touch instead of the updated_at/on attributes.
# Please note that no validation is performed and no callbacks are executed.
# If an attribute name is passed, that attribute is updated along with
# updated_at/on attributes.
#
# Examples:
#
# product.touch # updates updated_at
# product.touch(:designed_at) # updates the designed_at attribute
# product.touch # updates updated_at/on
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
def touch(attribute = nil)
current_time = current_time_from_proper_timezone
if attribute
write_attribute(attribute, current_time)
self.update_attribute(attribute, current_time)
else
timestamp_attributes_for_update_in_model.each { |column| write_attribute(column.to_s, current_time) }
timestamp_attributes_for_update_in_model.each { |column| self.update_attribute(column, current_time) }
end
save!
end
private

View File

@@ -25,16 +25,26 @@ class TimestampTest < ActiveRecord::TestCase
end
def test_touching_a_record_updates_its_timestamp
previous_salary = @developer.salary
@developer.salary = previous_salary + 10000
@developer.touch
assert_not_equal @previously_updated_at, @developer.updated_at
assert_equal previous_salary + 10000, @developer.salary
assert @developer.salary_changed?, 'developer salary should have changed'
assert @developer.changed?, 'developer should be marked as changed'
@developer.reload
assert_equal previous_salary, @developer.salary
end
def test_touching_a_different_attribute
previously_created_at = @developer.created_at
@developer.touch(:created_at)
assert !@developer.created_at_changed? , 'created_at should not be changed'
assert !@developer.changed?, 'record should not be changed'
assert_not_equal previously_created_at, @developer.created_at
assert_not_equal @previously_updated_at, @developer.updated_at
end
def test_saving_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_update_the_parent_updated_at