# storing a hash in the data base

**URL:** <https://discuss.rubyonrails.org/t/storing-a-hash-in-the-data-base/21667>\
**Category:** rubyonrails-talk\
**Created:** [December 13, 2007, 1:10pm UTC](https://discuss.rubyonrails.org/t/storing-a-hash-in-the-data-base/21667 "2007-12-13T13:10:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Michael\_Bleigh](https://avatars.discourse-cdn.com/v4/letter/m/b3f665/32.png) [@Michael\_Bleigh](https://discuss.rubyonrails.org/u/Michael_Bleigh)\
**Post date:** [December 13, 2007, 1:10pm UTC](https://discuss.rubyonrails.org/t/storing-a-hash-in-the-data-base/21667/1 "2007-12-13T13:10:18Z")

</div>

Gady,

This is a perfect area where Ruby can work its magic. Here's an  
example of what you could do:

class Element \< ActiveRecord::Base &nbsp;&nbsp;&nbsp;has\_many :variables

&nbsp;&nbsp;&nbsp;def (name) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;variables.find\_by\_name(name) &nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;def =(name,value) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var = variables.find\_or\_create\_by\_name(name) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var.value = value &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var.save &nbsp;&nbsp;&nbsp;end end

class Variable \< ActiveRecord::Base &nbsp;&nbsp;&nbsp;belongs\_to :element end

Now you will be able to do the following:

e = Element.create e["x"] = 800 e["y"] = 600 e["whatever"] = "anything"

e["x"] #-\> "800" e["y"] #-\> "600" e["whatever"] #-\> "anything"

Isn't that fantastic? Note that this is assuming that your value field  
is a TEXT which will return anything as a string. You could also store  
a type and coerce the values, let me know if you want more detail.

Michael Bleigh michael@intridea.com
