How do I retrieve specific attributes of a relationship/collection?

attributes, collections, relationship, ruby, ruby-on-rails

Solution

If `cars` is an association of a `person`, and `name` a property of a `car`, then you can do the following:

# person = Person.find(conditions)
person.cars.collect { |car| car.name }

Or even (thanks to `ActiveSupport` and/or Ruby 1.9):

person.cars.collect(&:name)

Update: this is documented in the following places:

- Association proxy for `has_many` returns `Array`

- `Array#collect`

- `Symbol#to_proc` in `ActiveSupport`, used in the second example

- `Symbol#to_proc` in Ruby 1.9

Update 2: an example that applies formatting:

person.cars.collect { |car| "(#{car.name})" }

Problem

Is there a good way to retrieve all of a specific attribute from a relationship/collection? For instance, I want a list of all the names of a person's cars. Obviously I can't do the following: Person.Cars.Name(s) ...but does something of that nature exist in ruby (or is there an ActiveRecord helper method) that handles that? Obviously I could iterate over all the cars and append to an array, but I'd like something a bit cleaner. Any ideas? Best.

Original source