1

Company model: There is aa attribute name and company has_many users.

Users model: User belongs to company.

Query:

After the query execution, below is my result.

users = {1360=>[#<User id: 2183, company_id: 1360, name: "XYS">, #<User id: 2184, company_id: 1360, name: "XYS1">], 1361=>[#<User id: 2185, company_id: 1361, name: "ABC">]}

In users object, there is one more column that is company_name which is fetch in query as alias, because I want only company_name not other attributes.

users = {1360=>[#<User id: 2183, company_id: 1360, name: "XYS", company_name="One">, #<User id: 2183, company_id: 1360, name: "XYS", company_name="One">], 1361=>[#<User id: 2185, company_id: 1361, name: "ABC", company_name="Two">]}

Here is the my desired output. (Key would be company_name and its velue will be array of users info(name and id))

users = {"One"=>[["XYS", 2183], ["XYS1", 2184]], "Two"=>[["ABC", 2185]]}

How can I do that. Because when I try to replace the key(id) with name throughs an error

2
  • What is the error that you get when you replace key(id)? Also, from where do you get this: "One" and "Two"? in your desired result? Commented Jul 3, 2015 at 8:43
  • One and Two are the companies name. I am fetching the users in which I have fetch one more column that the name(as company_name). Commented Jul 3, 2015 at 8:47

1 Answer 1

2

Try this

users.map{  |_,array| [array.first.company_name, array.map{ |a| [a.name, a.id] }] }.to_h
Sign up to request clarification or add additional context in comments.

5 Comments

There is ] missing?
Technically, this is not "replacing the key", though :)
v is an array. How can we call company_name on array?
@PiotrKruczek - Still having a problem. If both companies have same name (One) coincidentally. Then out put is wrong!
Then you need to change the expected output. Hashes need to have unique keys!

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.