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.
app/model/country.rb
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]
result
end
end
end
Now you can get the hash object by
@countries = Country.hashify
This the the resulted country hash.
{
"Afghanistan"=>"AF",
"Aland Islands"=>"AX",
"Albania"=>"AL",
...
"Zambia"=>"ZM",
"Zimbabwe"=>"ZW"
}
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.

A simpliest way is:
@country_hash = Hash[*Country.all.collect {|it| [it.name, it.code]}.flatten]LikeLike
Thanks for your code. i have included it in this post. =D
LikeLike
On Rails 3 or later, you can use #serializable_hash like this
@country_hash = Hash[*Country.all.serializable_hash(only: [:name, :code])]
LikeLike
thanks for your suggestion~ =)
LikeLike