# Automatic marshalling with DB access

**URL:** <https://www.ruby-forum.com/t/automatic-marshalling-with-db-access/119373>\
**Category:** Rails\
**Created:** [November 6, 2007, 3:01pm UTC](https://www.ruby-forum.com/t/automatic-marshalling-with-db-access/119373 "2007-11-06T15:01:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [November 6, 2007, 3:01pm UTC](https://www.ruby-forum.com/t/automatic-marshalling-with-db-access/119373/1 "2007-11-06T15:01:48Z")

</div>

I have an item which has a hash for one of its fields. When i store it  
in the db, i want to do a Marshal.dump of the hash, and similarly, do a  
Marshal.load to turn the saved blob back into a hash again.

Is there a way to easily write this into the model, so that it happens  
automatically when saving and loading a record?

thanks  
max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [November 7, 2007, 2:00am UTC](https://www.ruby-forum.com/t/automatic-marshalling-with-db-access/119373/2 "2007-11-07T02:00:43Z")

</div>

On Nov 6, 2007 9:01 AM, Max W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> I have an item which has a hash for one of its fields. When i store it  
> in the db, i want to do a Marshal.dump of the hash, and similarly, do a  
> Marshal.load to turn the saved blob back into a hash again.
> 
> Is there a way to easily write this into the model, so that it happens  
> automatically when saving and loading a record?
> 
> thanks  
> max

Check out ActiveRecord::Base.serialize

> **[ActiveRecord::Base](https://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001020)**
>
> Active Record Active Record objects don't specify their attributes directly, but rather infer them from the table definition with which they're linked.

class Foo \< ActiveRecord::Base  
serialize :bar  
end

HTH,  
Michael G.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [November 7, 2007, 11:21am UTC](https://www.ruby-forum.com/t/automatic-marshalling-with-db-access/119373/3 "2007-11-07T11:21:26Z")

</div>

Michael G. wrote:

> Check out ActiveRecord::Base.serialize
> 
> [ActiveRecord::Base](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001020)
> 
> class Foo \< ActiveRecord::Base  
> serialize :bar  
> end
> 
> HTH,  
> Michael G.

Yeah, i just discovered that as well, it’s exactly what i was after,  
cheers!
