Rails – Retrieve a Hash from Model

I would like to add a selection list country field in a view but first i need to get the a country hash from the Country model.

In Rails ActiveRecord, the Model.find() method returns an array
of objects from the database, so what i need to do is converting the returned array into a hash object and i have already talked about this in the previous post
Ruby – Convert Array into Hash

But the array which i get from the ActiveRecord is not the same as the above example. Anyway, the following did work for me to get a country hash.

class Country < ActiveRecord::Base

  def self.hashify
    @country_array = Country.find(:all, :select => 'name, code').to_a
    @country_hash = @country_array.inject({}) do |result, element|
      result[element[:name]] = element[:code]


Now you can get the hash object by

@countries = Country.hashify


This the the resulted country hash.

  "Aland Islands"=>"AX",


Done =)

Update 2012-03-08: A simpler way to get the hash object suggested by Filipe as follow.

@country_hash = Hash[*Country.all.collect {|it| [it.name, it.code]}.flatten]

Thanks Filipe.

5 thoughts on “Rails – Retrieve a Hash from Model”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.