# Serializing an AR object into an attribute in another

**URL:** <https://www.ruby-forum.com/t/serializing-an-ar-object-into-an-attribute-in-another/148527>\
**Category:** Rails\
**Created:** [September 14, 2008, 10:01am UTC](https://www.ruby-forum.com/t/serializing-an-ar-object-into-an-attribute-in-another/148527 "2008-09-14T10:01:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jmcervera](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/51bf81/32.png) [@jmcervera](https://www.ruby-forum.com/u/jmcervera)\
**Post date:** [September 14, 2008, 10:01am UTC](https://www.ruby-forum.com/t/serializing-an-ar-object-into-an-attribute-in-another/148527/1 "2008-09-14T10:01:23Z")

</div>

Hi,

I don’t know if this is a bug or it is the expected behavior but I am  
trying to serialize an AR object into another.  
I know this is not very usual but I don’t want to use a belongs\_to  
association because the object is transient.  
I need an snapshot of how the 2nd object was at the moment of the  
creation of the 1st.

class One \< ActiveRecord::Base  
end

class Two \< ActiveRecord::Base  
serialize one  
end

obj1 = One.find(:first)  
obj2 = Two.create(…)  
obj2.one = obj1  
obj2.save

My problem is that it seems that AectiveRecord only saves the id of the  
serialized object when create or update the second object and not all  
the yaml format of the serialized.  
There is not any association between the two objects.

Anyone knows if I am on the right track? Or I need to change the  
direction?

Thanks  
Juanma C.

---

<div class="post-metadata">

**Author:** ![jmcervera](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/51bf81/32.png) [@jmcervera](https://www.ruby-forum.com/u/jmcervera)\
**Post date:** [September 14, 2008, 11:31am UTC](https://www.ruby-forum.com/t/serializing-an-ar-object-into-an-attribute-in-another/148527/2 "2008-09-14T11:31:08Z")

</div>

You might want to try doing your own “serializing”.

class Two \< ActiveRecord::Base  
def one=(new\_one)  
self.write\_attribute(:one, new\_one.to\_yaml)  
end  
def one  
@one ||= YAML.load(self.read\_attribute(:one))  
end  
end

I haven’t tested this, but it might be a place to start.

---

<div class="post-metadata">

**Author:** ![jmcervera](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/51bf81/32.png) [@jmcervera](https://www.ruby-forum.com/u/jmcervera)\
**Post date:** [September 14, 2008, 7:08pm UTC](https://www.ruby-forum.com/t/serializing-an-ar-object-into-an-attribute-in-another/148527/3 "2008-09-14T19:08:44Z")

</div>

It has been easy with your help.  
Many thanks.
