开发者

How to map more than one Attribute with ActiveRecord?

开发者 https://www.devze.com 2023-01-06 21:50 出处:网络
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

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

精彩评论

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

关注公众号