gadys
December 13, 2007, 1:38pm
1
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/ ?
gadys
December 13, 2007, 2:10pm
2
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]
gadys
December 13, 2007, 2:55pm
3
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
gadys
December 14, 2007, 1:41pm
4
Sorry, forgot to mention that ‘variables’ must be a text attribute on
Element.
gadys
December 14, 2007, 1:38pm
5
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]