开发者

How to map more than one Attribute with ActiveRecord?

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 tried

u.friends(&map:username, &map:birthday)

but this doesn't work.


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.


With ActiveRecord >= 4 you can simply use:

u.friends.pluck(:username, :birthday)


Try

u.friends.map {|friend| [friend.username, friend.birthday]}

The & syntax is simply a shorthand to the underlying Ruby method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜