ActiveRecord Object to Hash assignment in Ruby on Rails


07.13.10 Posted in Blog by admin

I find a frequent scenario in Ruby on Rails code base. A local hash variable is assigned a partial subset of an ActiveRecord object, or worse the variable gets the entire AR object. And may be you don’t already do it the way I have seen it, but its still worth discussing, being as frequent a requirement as it is.

1. If we want to assign an entire AR object to a local hash:
A direct assignment is possible with “attributes”

local_hash = session_user.attributes

the ‘local_hash’ now has an attribute-value hash of the session_user object, an ActiveRecord object of model User ]

2. If we need the local_hash to have only a subset of the AR object attributes:

desired_keys = ['address' , 'zipcode' , 'city' , 'country']
local_array = session_user.attributes.select{|key,value| desired_keys.include?(key) }
local_hash = Hash[*local_array.flatten]

the ‘local_hash’ now has only the desired attribute values. This can easily be extended by simply adding more keys to ‘desired_keys’.
Instead of what I usually see,

local_hash = {
'address' => session_user.address,
'zipcode' => session_user.zipcode,
'city' => session_user.city,
'country' => session_user.country
}

What do you think of this snippet? Is there a shorter/smarter way of doing this? Think on!



One Response to “ActiveRecord Object to Hash assignment in Ruby on Rails”

  1. Alex Mercer says:

    you can use hash in more simplier way.. with `except` method

    instead of:
    desired_keys = ['address' , 'zipcode' , 'city' , 'country']
    local_array = session_user.attributes.select{|key,value| desired_keys.include?(key) }
    local_hash = Hash[*local_array.flatten]

    you can use:
    # ‘name’, ‘id’ – fields that you don’t wanna to see in `local_hash`
    local_hash = session_user.attributes.except(‘name’, ‘id’)

Leave a Reply

 
May 2012
M T W T F S S
« Dec    
 123456
78910111213
14151617181920
21222324252627
28293031  
Social Media
Get in Touch
contact[at]jigyasamakkar[dot]com