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

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})" }