Reputation: 1608
I have a model Person with fields email, name, age, phone_number. I want to convert Person.all
to a hash.
The hash should have the structure as follows:
{
"email1" => ["name", "age", "phone_number"],
"email2" => ["name2", "age2", "phone_number2"]
....
}
I tried as_json
, map
or attributes
etc. But it returns array of hashes. How can I create this custom structure?
Upvotes: 3
Views: 3437
Reputation: 5552
You can get it from below query,
Hash[Person.all.collect { |user| [user.email, user.attributes.except(:email).values] }]
If you want to omit other attributes like created_at
& updated_at
, run
Hash[Person.all.collect { |user| [user.email, user.attributes.except(:email, :created_at, :updated_at).values] }]
Upvotes: 5