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
carsis an association of aperson, andnamea property of acar, then you can do the following:Or even (thanks to
ActiveSupportand/or Ruby 1.9):Update: this is documented in the following places:
has_manyreturnsArrayArray#collectSymbol#to_procinActiveSupport, used in the second exampleSymbol#to_procin Ruby 1.9Update 2: an example that applies formatting: