David Tashima
2006-Mar-27 04:24 UTC
[Rails] Is there a way to persist a Hash in ActiveRecord?
I can''t seem to figure out a way to persist a hash attribute in ActiveRecord. Let''s say I have a Game, which has a many-to-many with players. Each player has an index, but the array can have empty spaces in it (since a game might not be filled up yet). I''d like to model this using a hash, with position --> player mapping. (What I don''t want to do is create a "nil" player). In Hibernate, you would do this with <map>... is there an ActiveRecord equivalent? Thanks, Dave -- Posted via http://www.ruby-forum.com/.
Wilson Bilkovich
2006-Mar-27 05:21 UTC
[Rails] Is there a way to persist a Hash in ActiveRecord?
On 3/26/06, David Tashima <tash@speakeasy.net> wrote:> > I can''t seem to figure out a way to persist a hash attribute in > ActiveRecord. Let''s say I have a Game, which has a many-to-many with > players. > > Each player has an index, but the array can have empty spaces in it > (since a game might not be filled up yet). > > I''d like to model this using a hash, with position --> player mapping. > > (What I don''t want to do is create a "nil" player). > > In Hibernate, you would do this with <map>... is there an ActiveRecord > equivalent? > > Thanks, > Dave >It should ''just work'', by converting the Hash to YAML, if you assign it to an attribute that maps to a varchar/CLOB column. If that doesn''t work because I''m crazy and misremembering something, you could do it ''manually'' by calling to_yaml on your Hash as part of the before_save callback. I remember that there''s a case statement somewhere in the ActiveRecord code that decides what to do with an attribute based on its Ruby type.. and the "else" branch converts it to YAML.