Nidhin Bose J.
Nidhin Bose J.

Reputation: 1092

create a hash in an array with values from database

i have firstname,lastname and id of a list of people in database. Now i want to make an array like

[{
  value: <corresponding id>,
  label: "<corresponding person name>"
 },
 {
  value: <corresponding id>,
  label: "<corresponding person name>"
 },
  ....
]

Upvotes: 0

Views: 3136

Answers (1)

Salil
Salil

Reputation: 47472

users = User.all
user_hash_array = users.collect{|user| {:value => user.id, :label => user.firstname}}

This will work like following

id   firstname   lastname
1    Salil       Gaikwad
2    Nidhin      Bose

This will gives you following

user_hash_array = [{:value=>1, :label=>"Salil"}, {:value=>2, :label=>"Nidhin"}]

Upvotes: 3

Related Questions