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.
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:
has_many
returns Array
Array#collect
Symbol#to_proc
in ActiveSupport
, used in the second exampleSymbol#to_proc
in Ruby 1.9Update 2: an example that applies formatting:
person.cars.collect { |car| "(#{car.name})" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With