Storing a hash in the data base

Hi
I’m new to rails and I want to create an object named element with can
hold sevral properties names and values.
for example :

e = Element.create()
e.add(:name => “x”, :value => 800)
e.add(:name => “y”, :value => 600)
e.add(:name => “whatever”, :value => “anything”)

e.get(:name => “x”) #-> 800
e.get(:name => “y”) #-> 300
e.get(:name => “whatever”) #-> anything

i was thinkings add the object var which holds (id, element_id, name,
value)
with a relationship of element has_many vars.
how do i create the getter ? (e.get(:name => “x”)
and the setter ?

thanks.

anyone used this plugin http://svn.nkryptic.com/ ?

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
has_many :variables

def
variables.find_by_name(name)
end

def []=(name,value)
var = variables.find_or_create_by_name(name)
var.value = value
var.save
end
end

class Variable < ActiveRecord::Base
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 B.
[email protected]

Thanks allot.
never thought it can be that easy…
there is a small bug. it need to be

def
variables.find_by_name(name).value
end

Michael B. wrote:

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
has_many :variables

def
variables.find_by_name(name)
end

Sorry, forgot to mention that ‘variables’ must be a text attribute on
Element.

Hi Gady,

Another (much lighter) way of doing this is with the
'serliaze’declaration, that serializes hashes or arrays automagically.

class Element < ActiveRecord::Base
serialize :variables
end

Then you can just do setters with:

element.variables = {:price => ‘4’, :availability => ‘7 Days’}
element.save

And the getter becomes:
element.variables[:price]

This way, you don’t need additional classes, tables or relationships.

Matt

On Dec 13, 10:38 pm, Gady S. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs