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 2008-02-10 03:07
on 2008-02-10 03:09
On Feb 9, 2008 6:06 PM, Bill Kocik <bkocik@gmail.com> 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 Olson http://lighthouseapp.com http://weblog.techno-weenie.net http://mephistoblog.com
on 2008-02-10 03:12
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}
on 2008-02-10 15:20
> 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 2008-02-20 11:51
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
on 2012-07-14 14:07
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 http://guides.rubyonrails.org/active_record_queryi...
Please log in before posting. Registration is free and takes only a minute.
Existing account
(Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
Log in with Google account | Log in with Yahoo account
No account? Register here.