In my app, each item has, among other attributes, a hash containing 3 elements. When I set the hash and save the item, the hash is saved as a string. Which is fine. When I pull the item from the database, it''s still a string. Reparsing the string seems very un-Ruby-like. Is there an automagical way to return the 3 elements to a hash? -- Garrick Van Buren ---------------------------------------------------- garrick.vanburen-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org ph: 612 325 9110 ----------------------------------------------------- First Crack Podcast http://firstcrackpodcast.com/ -----------------------------------------------------
I had to deal with this lately. In your model, use: serialize table_column and Rails will handle the serialization of the hash item automagically. On Sep 27, 2005, at 11:03 AM, Garrick Van Buren wrote:> In my app, each item has, among other attributes, a hash containing 3 > elements. When I set the hash and save the item, the hash is saved as > a string. Which is fine. > > When I pull the item from the database, it''s still a string. > > Reparsing the string seems very un-Ruby-like. Is there an automagical > way to return the 3 elements to a hash? > > > -- > Garrick Van Buren > ---------------------------------------------------- > garrick.vanburen-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org > ph: 612 325 9110 > ----------------------------------------------------- > First Crack Podcast > http://firstcrackpodcast.com/ > ----------------------------------------------------- > _______________________________________________ > Rails mailing list > Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org > http://lists.rubyonrails.org/mailman/listinfo/rails > >
On 9/27/05, Garrick Van Buren <garrick.vanburen-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> In my app, each item has, among other attributes, a hash containing 3 > elements. When I set the hash and save the item, the hash is saved as > a string. Which is fine. > > When I pull the item from the database, it''s still a string. > > Reparsing the string seems very un-Ruby-like. Is there an automagical > way to return the 3 elements to a hash?Depending on what the hash looks like in the db, you could use eval: hashstring = "{\"key1\"=>\"value1\", \"key2\"=>\"value2\"}" myhash = eval(hashstring)
On 9/27/05, Garrick Van Buren <garrick.vanburen-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> In my app, each item has, among other attributes, a hash containing 3 > elements. When I set the hash and save the item, the hash is saved as > a string. Which is fine. > > When I pull the item from the database, it''s still a string. > > Reparsing the string seems very un-Ruby-like. Is there an automagical > way to return the 3 elements to a hash?Ah, I didn''t know that this was built into rails. Check the ActiveRecord docs for "serialize". There''s an example there that is probably pretty close to what you need. http://api.rubyonrails.com/classes/ActiveRecord/Base.html