Skip to content
Browse files

Merge pull request #9320 from wangjohn/touch_handling_on_new_instances

Raising an ActiveRecordError when one tries to use touch on a new record object
  • Loading branch information...
2 parents 3762ee0 + e52ff80 commit 3285c76557f1c36aba4de17d3440e16220cd87d8 @guilleiguaran guilleiguaran committed
View
11 activerecord/CHANGELOG.md
@@ -1,5 +1,16 @@
## Rails 4.0.0 (unreleased) ##
+* Fixing issue #8345. Now throwing an error when one attempts to touch a
+ new object that has not yet been persisted. For instance:
+
+ ball = Ball.new
+ ball.touch :updated_at # => raises error
+
+ It is not until the ball object has been persisted that it can be touched.
+ This follows the behavior of update_column.
+
+ *John Wang*
+
* Preloading ordered `has_many :through` associations no longer applies
invalid ordering to the `:through` association.
Fixes #8663.
View
2 activerecord/lib/active_record/persistence.rb
@@ -368,6 +368,8 @@ def reload(options = nil)
# # triggers @brake.car.touch and @brake.car.corporation.touch
# @brake.touch
def touch(name = nil)
+ raise ActiveRecordError, "can not touch on a new record object" unless persisted?
+
attributes = timestamp_attributes_for_update_in_model
attributes << name if name
View
7 activerecord/test/cases/base_test.rb
@@ -1447,6 +1447,13 @@ def test_cache_key_format_for_existing_record_with_nil_updated_at
assert_match(/\/#{dev.id}$/, dev.cache_key)
end
+ def test_touch_should_raise_error_on_a_new_object
+ company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
+ assert_raises(ActiveRecord::ActiveRecordError) do
+ company.touch :updated_at
+ end
+ end
+
def test_cache_key_format_is_precise_enough
dev = Developer.first
key = dev.cache_key

0 comments on commit 3285c76

Please sign in to comment.
Something went wrong with that request. Please try again.