I have data stored in an array and all elements are of the same type.
Example:
myarray = [1, 2, 3]
This data will be stored in a text column, array_as_string, of an
Object.
class Object < ActiveRecord::Base
So with an instance of Object, I save myarray by creating a
space-delimited string
myobject = Object.new(:array_as_string => myarray.join(' '))
myobject.save
Updating is similar. I can then later retrieve the data by splitting
the string and converting the string data.
myotherarray = myobject.array_as_string.split.collect { |elem|
elem.to_i }
What I'd like to know is there an easier and hopefully more automatic
way of doing this? Is there a helper that already exists to do this
and that may even detect the type of the element?
Brian Gibson wrote:
I have data stored in an array and all elements are of the same type.
Example:
myarray = [1, 2, 3]
This data will be stored in a text column, array_as_string, of an
Object.
class Object < ActiveRecord::Base
So with an instance of Object, I save myarray by creating a
space-delimited string
myobject = Object.new(:array_as_string => myarray.join(' '))
myobject.save
Updating is similar. I can then later retrieve the data by splitting
the string and converting the string data.
myotherarray = myobject.array_as_string.split.collect { |elem|
elem.to_i }
What I'd like to know is there an easier and hopefully more automatic
way of doing this? Is there a helper that already exists to do this
and that may even detect the type of the element?
class Foo < ActiveRecord::Base
serialize :bar, Array
end
f = Foo.find(:first)
f.bar = [1, "ttt" , 3]
f.save
f.reload!
f.bar => [1, "ttt", 3]
enjoy,
Zsombor