Bug in initialize_copy

7 views
Skip to first unread message

throwern

unread,
Aug 9, 2011, 9:44:20 AM8/9/11
to Composite Keys for ActiveRecord
I think there is a bug in initialize_copy.

Using CPK 3.1.10 , ruby 1.9.2 and Rails 3.0.9

Calling dup on a composite object will maintain a reference to the
original @changed_attributes instance.
This can cause errors during update if the @changed_attributes of the
clone are edited.

I found this because PaperTrail(2.2.9) uses object.dup and manipulates
the @changed_attributes to store versions:

previous = self.dup
previous.tap do |prev|
prev.id = id
changed_attributes.each { |attr, before| prev[attr] = before }
end


The Following code (from ActiveRecord::Base) added to the end of the
current initialize_copy method seems to fix the problem.

@changed_attributes = {}
super(*args).tap{
attributes_from_column_definition.each do |attr, orig_value|
@changed_attributes[attr] = orig_value if field_changed?(attr,
orig_value, @attributes[attr])
end
}

Is there a reason the @changed_attributes hash assignment was left out
of initialize_copy?

throwern

unread,
Aug 9, 2011, 9:50:36 AM8/9/11
to compos...@googlegroups.com
Oops, that code won't fix the bug. You need the following (without the call to super)

@changed_attributes = {}

cfis

unread,
Aug 31, 2011, 3:45:15 PM8/31/11
to Composite Keys for ActiveRecord
Hi throwern,

Could you submit a pull request?

Thanks - Charlie
Reply all
Reply to author
Forward
0 new messages