Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Dup reset timestamps #113

Closed
wants to merge 2 commits into from

3 participants

@franckverrot

The last changes in the CHANGELOG makes it clear that AR::Base.dup returns an object where new_record? is true. The attached patch clears the timestamps (if they exist) when calling dup. If we don't want that behavior though, we should document that dup preserves these AR-managed attributes.

In any case we should also close/mark as invalid that ticket AR::Clone does not clear out timestamps

@fxn
Owner

I think the docs should also mention the details about callbacks.

@tenderlove
Owner

@cesario perfect, thanks. I will apply this.

@fxn Not sure where we document this stuff. The behavior of dup is basically what clone used to do. If we documented clone somewhere, we need to change it to say "dup".

@franckverrot

Here's another pull request documenting the dup behavior, and fixing the typo.
#114

Thanks!

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
View
11 activerecord/lib/active_record/base.rb
@@ -1625,6 +1625,7 @@ def initialize_dup(other)
ensure_proper_type
populate_with_current_scope_attributes
+ clear_timestamp_attributes
end
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
@@ -1831,6 +1832,16 @@ def populate_with_current_scope_attributes
create_with.each { |att,value| self.respond_to?(:"#{att}=") && self.send("#{att}=", value) } if create_with
end
end
+
+ # Clear attributes and changged_attributes
+ def clear_timestamp_attributes
+ %w(created_at created_on updated_at updated_on).each do |attribute_name|
+ if self.has_attribute?(attribute_name)
+ self[attribute_name] = nil
+ self.changed_attributes.delete(attribute_name)
+ end
+ end
+ end
end
Base.class_eval do
View
24 activerecord/test/cases/dup_test.rb
@@ -51,7 +51,12 @@ def test_dup_with_changes
topic.attributes = dbtopic.attributes
+ #duped has no timestamp values
duped = dbtopic.dup
+
+ #clear topic timestamp values
+ topic.send(:clear_timestamp_attributes)
+
assert_equal topic.changes, duped.changes
end
@@ -75,5 +80,24 @@ def test_dup_attributes_are_independent
assert_equal 'Aaron', topic.author_name
assert_equal 'meow', duped.author_name
end
+
+ def test_dup_timestamps_are_cleared
+ topic = Topic.first
+ assert_not_nil topic.updated_at
+ assert_not_nil topic.created_at
+
+ # temporary change to the topic object
+ topic.updated_at -= 3.days
+
+ #dup should not preserve the timestamps if present
+ new_topic = topic.dup
+ assert_nil new_topic.updated_at
+ assert_nil new_topic.created_at
+
+ new_topic.save
+ assert_not_nil new_topic.updated_at
+ assert_not_nil new_topic.created_at
+ end
+
end
end
Something went wrong with that request. Please try again.