# Associating to a hash?

**URL:** <https://www.ruby-forum.com/t/associating-to-a-hash/88941>\
**Category:** Rails\
**Created:** [March 15, 2007, 7:03pm UTC](https://www.ruby-forum.com/t/associating-to-a-hash/88941 "2007-03-15T19:03:06Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tyler\_MacDonald](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/b5ac83/32.png) [@Tyler\_MacDonald](https://www.ruby-forum.com/u/Tyler_MacDonald)\
**Post date:** [March 15, 2007, 7:03pm UTC](https://www.ruby-forum.com/t/associating-to-a-hash/88941/1 "2007-03-15T19:03:06Z")

</div>

I’m setting up my users’ profiles as a set of key/value pairs…  
where each key/value pair is a row in an associated table, like so:

user\_id  
profile\_key  
value

The profile\_keys themselves are associations to a “profile\_keys”  
table (yea, way too organized, I know. 😉

For some syntax sugar, I’ve set up some methods on the “profile”  
has\_many association on the user:

```
def [](k)
  return fetch(socialize(k))
end

def []=(k, v)
  kk = socialize k
  user = @owner
  if entry = fetch_object(kk)
    entry.value = v
  else
    entry = UserProfile.new(
      :profile_key => kk, :value => v, :user => user
    )
  end
  entry.save
  return entry
end

def socialize(key)
  if key.class == Fixnum
    key = UserProfileKey.find key
  elsif key.class == String or key.class == Symbol
    key = UserProfileKey.find_by_name key.to_s
  end
  return key
end

def fetch_object(profile_key)
  result = self.collect { |x| x if x.profile_key == profile_key }
  result.compact!
  if v = result.first
    return v
  else
    return nil
  end
end

def fetch(profile_key)
  if v = fetch_object(profile_key)
    return v.value
  else
    return nil
  end
end

```

Before I go too much further down this path… I’m _sure_ somebody  
else out there has set up an associated key/value pair table… is there  
some published prior art on this? A plugin perhaps? (If not, the end  
result  
is probably going to be me writing one… 😉

Thanks,  
Tyler
