ActiveRecord - return array of only ids?

Is it possible to get ActiveRecord to run a query and return an array
of only the ids of the rows that matched? It seems to insist on giving
me back an array of objects, even if I specify “:select => ‘id’” as
part of my find(). I don’t want to have to loop over the objects
getting all the ids if I don’t have to. Can’t AR be coaxed into
returning ids and only ids?

I’ve pored over documentation and searched the web and I haven’t
really come up with much. Thought I’d try you all.

Thanks,
-Bill

On Feb 9, 2008 6:06 PM, Bill K. [email protected] wrote:

really come up with much. Thought I’d try you all.
You’ll need to drop back to the raw adapter for a custom query. #find
is only interested in dealing with ActiveRecord instances.

Foo.connection.select_values “SELECT id FROM foos …”


Rick O.
http://lighthouseapp.com
http://weblog.techno-weenie.net
http://mephistoblog.com

Object.find(:all, :select => ‘id’) works but I don’t think that is
what you really want.

You want [1,2,3,4,5], correct?

If so, you can do Object.find(:all,:select=>‘id’).map {|x| x.id}

Object.find(:all, :select => ‘id’) works but I don’t think that is
what you really want.

You want [1,2,3,4,5], correct?

If so, you can do Object.find(:all,:select=>‘id’).map {|x| x.id}

You can alos use symbol to proc trick here:

Object.find(:all,:select=>‘id’).map(&:id)

Regards,
Rimantas

http://rimantas.com/

On Sat, 09 Feb 2008 18:12:00 -0800, brewpoo wrote:

If so, you can do Object.find(:all,:select=>‘id’).map {|x| x.id}

How do I find out about the magic of “map”?

thanks,

Thufir

Excellent suggestions, everyone. Thank you!

http://www.ruby-doc.org/core/classes/Enumerable.html#M003159

http://tech.rufy.com/2006/11/functional-programming-in-ruby.html

Should anyone else come across this, another way to refine this further
is:

Object.pluck(:id)

This will produce your array of ids.

More here