DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Active Record To_hash

12.05.2006
| 7796 views |
  • submit to reddit
        With this mix-in, you can have nice "to_hash" methods on your active record objects.  

I find it good for programming JSON apps.

In lib/ar_hashing.rb
module ActiveRecordHashing
  def to_hash
      Hash[*self.map{ |m| [m.id, m]}.flatten]               
  end
end

and in config/environment.rb
require 'ar_hashing'

class ActiveRecord::Associations::AssociationCollection
  include ActiveRecordHashing
end
    

Comments

Snippets Manager replied on Fri, 2010/02/19 - 12:41am

This didn't work for me, but I just used ActiveRecord's `attributes` method