How to map more than one Attribute with ActiveRecord?
22,274
Solution 1
You can use the alternate block syntax:
u.friends.map{|f| [f.username, f.birthday]}
which would give an array of arrays.
u.friends.map{|f| "#{f.username} - #{f.birthday}"}
would give you an array of strings. You can do quite a bit from there.
Solution 2
With ActiveRecord >= 4 you can simply use:
u.friends.pluck(:username, :birthday)
Solution 3
Try
u.friends.map {|friend| [friend.username, friend.birthday]}
The &
syntax is simply a shorthand to the underlying Ruby method.
Author by
tabaluga
Updated on September 19, 2020Comments
-
tabaluga over 3 years
If I type in my console
u = User.first u.friends(&map:username)
I get
["Peter", "Mary", "Jane"]
but I also want to show the birthday, so how do I do that? I triedu.friends(&map:username, &map:birthday)
but this doesn't work.