5

I know that Person.find(:all) returns an array of Person objects but is there somehow I can just get 'name' property of all people in the Person table?

Something like

        Person.find(:all).names
theReverseFlick
  • 5,894
  • 8
  • 32
  • 33

1 Answers1

6

Use :select to retrieve only specific attributes.

Person.all(:select => :name)

Would give you person objects that only have the name attribute initialized. Then you can map/collect that attribute to get the array of names.

futuremint
  • 724
  • 4
  • 5
  • 3
    One less step: `Person.all.collect(&:name)` – varatis Jun 26 '12 at 18:26
  • 1
    This is a nice approach, why do you have to use the `&` for `&:name`? – Besi May 16 '14 at 13:14
  • 1
    @Besi it's a shorthand way of doing `Person.all.collect { |p| p.name }` or the following three-liner: `Person.all.collect do |p|` `p.name` `end` This is a good explanation: http://stackoverflow.com/a/9468624/444681 – Lou Alicegary Mar 06 '15 at 02:53