Forum: Ruby on Rails Is there a way to persist a Hash in ActiveRecord?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8ade3b1cd02e768e5eedc428c418a932?d=identicon&s=25 David Tashima (tash)
on 2006-03-27 06:24
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
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2006-03-27 07:21
(Received via mailing list)
On 3/26/06, David Tashima <tash@speakeasy.net> wrote:
> (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.
This topic is locked and can not be replied to.