Reputation: 334
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
Upvotes: 1
Views: 188
Reputation: 2390
Try this
users.map{ |_,array| [array.first.company_name, array.map{ |a| [a.name, a.id] }] }.to_h
Upvotes: 2