0

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>"
 },
  ....
]

1 Answer 1

3
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"}]
Sign up to request clarification or add additional context in comments.

4 Comments

thanks.how can i make it value: <corresponding id> unlike :value => <corresponding id> in your answer
In Ruby 1.9.3 {:value=>1} == {value:1} Try yourself from irb then type {value:1} and you will get {:value=>1}
In that case you can't get an hash like above.Just curious why you want such hash?
i am trying to implement something like this link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.