Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map more than one Attribute with ActiveRecord?

Tags:

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.

like image 279
tabaluga Avatar asked Jul 14 '10 08:07

tabaluga


People also ask

What is the difference between map and each in Ruby?

The difference between map and each is given as following: Array#each executes the given block for each element of the array, then returns the array itself. Array#map also executes the given block for each element of the array, but returns a new array whose values are the return values of each iteration of the block.

How map works in Ruby?

The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.

What is Activerecord in Ruby on Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

When to use map in Ruby?

Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.


2 Answers

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.

like image 163
Geoff Lanotte Avatar answered Oct 19 '22 07:10

Geoff Lanotte


With ActiveRecord >= 4 you can simply use:

u.friends.pluck(:username, :birthday) 
like image 42
techdreams Avatar answered Oct 19 '22 08:10

techdreams