Bill_Kocik
(Bill Kocik)
February 10, 2008, 2:06am
1
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
Rick_Olson
(Rick Olson)
February 10, 2008, 2:09am
2
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 ..."
brewpoo
(brewpoo)
February 10, 2008, 2:12am
3
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
Bill_Kocik
(Bill Kocik)
February 10, 2008, 6:22pm
5
Excellent suggestions, everyone. Thank you!
Thufir
(Thufir)
February 20, 2008, 10:50am
6
How do I find out about the magic of "map"?
thanks,
Thufir
11155
(-- --)
July 14, 2012, 12:07pm
8
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
Active Record Query InterfaceThis guide covers different ways to retrieve data from the database using Active Record.After reading this guide, you will know: How to find records using a variety of methods and conditions. How to specify the order,...