# ActiveRecord handling of obj.dup vs obj.clone

**URL:** <https://www.ruby-forum.com/t/activerecord-handling-of-obj-dup-vs-obj-clone/157312>\
**Category:** Rails\
**Created:** [January 9, 2009, 10:33am UTC](https://www.ruby-forum.com/t/activerecord-handling-of-obj-dup-vs-obj-clone/157312 "2009-01-09T10:33:06Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![daudi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/9e8a1a/32.png) [@daudi](https://www.ruby-forum.com/u/daudi)\
**Post date:** [January 9, 2009, 10:33am UTC](https://www.ruby-forum.com/t/activerecord-handling-of-obj-dup-vs-obj-clone/157312/1 "2009-01-09T10:33:06Z")

</div>

## AR seems to be handling model object dup and cloning differently from Ruby documented behavior. I’ve checked out both ways (as an AR model and not) and the behavior is different. I don’t see anything in the RAILS documentation about this. Am I missing something? is this a bug? a feature? an interesting lifestyle? I can hack around this difference but it is not elegant.

example 1 using AR:

class Model \< ActiveRecord::Base

# etc, normal model stuff, associations

def initialize\_copy(old\_obj)  
# do something  
end  
end

obj = Model.find(1)  
obj\_dup = obj.dup # does NOT yield a new object; does invoke  
obj\_dup.initialize\_copy(obj)

# at this point obj\_dup is same object as obj; any changes to obj\_dup

will change obj

# but obj\_dup changes have not been saved to DB yet

obj\_clone = obj.clone # does yield a new object; does NOT invoke  
obj\_clone.initialize\_copy(obj)

# at this point obj\_clone is a different object but not yet saved to

## DB

example 2 using pure Ruby:

class Test  
attr\_reader :name  
def initialize(str)  
@name = str  
end  
def initialize\_copy(old)  
@name += ’ \*\*\* COPY \*\*\*’  
end  
end

a = Test.new ‘john’ # a.name is now: ‘john’  
b = a.dup # b.name is now: ‘john \*\*\* COPY \*\*\*’  
c = a.clone # c.name is now: ‘john \*\*\* COPY \*\*\*’

# a, b, c are all DIFFERENT objects

# b.initialize\_copy(a) was invoked per Ruby documentation

# c.initialize\_copy(a) was invoked per Ruby documentation
