Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
humble_coder Avatar asked Jul 05 '09 23:07

humble_coder


1 Answers

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})" }
like image 77
molf Avatar answered Oct 11 '22 18:10

molf