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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

One less step: Person.all.collect(&:name)
This is a nice approach, why do you have to use the & for &:name?
@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: stackoverflow.com/a/9468624/444681

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.