Model.find(:all) - return a list of ids

Hi,

I currently call find(:all, …) on one of my models and it return a
page of models.

I am now looking at adding a memcached server and want the find(:all…)
to only return model ids, the models will be individually retrieved from
the cache.

Is this something that ActiveRecord supports or should I write a custom
bit of sql?

Thanks,
GiantCranes

On 4/12/07, Giant C. [email protected] wrote:

Is this something that ActiveRecord supports or should I write a custom
bit of sql?

You’ll have to write a bit of SQL for this, since it’s not really a
common operation. You can use the #select_values method of the
connection object:

Widget.connection.select_values(“select id from widgets”)


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

Thanks Rick, I’ll do just that then.

I currently call find(:all, …) on one of my models and it
return a page of models.

I am now looking at adding a memcached server and want the
find(:all…) to only return model ids, the models will be
individually retrieved from the cache.

Is this something that ActiveRecord supports or should I
write a custom bit of sql?

You can do custom sql, or use the :select option to limit the columns
returned:

model.find(:all, :select=>‘id’) returns an array of models with only the
ids loaded

model.find(:all, :select=>‘id’).collect(&:id) returns an array of ids

if you like using the rest of the find options to help generate your sql
for you.

  • donald

You can do custom sql, or use the :select option to limit the columns
returned:

model.find(:all, :select=>‘id’) returns an array of models with only the
ids loaded

model.find(:all, :select=>‘id’).collect(&:id) returns an array of ids

if you like using the rest of the find options to help generate your sql
for you.

  • donald

Sure, it does. But it creates an Object for each model, while raw SQL
gives you an Array of ids. From a performance perspective, the second
method is much better.

Thanks for the option donald, I hadn’t seen :select before.

I think I will go with the raw SQL option as this is an area of my
application that will be under load.

You can do custom sql, or use the :select option to limit the columns
returned:

model.find(:all, :select=>‘id’) returns an array of models with only the
ids loaded

model.find(:all, :select=>‘id’).collect(&:id) returns an array of ids

if you like using the rest of the find options to help generate your sql
for you.

  • donald

Sure, it does. But it creates an Object for each model, while raw SQL
gives you an Array of ids. From a performance perspective, the second
method is much better.

Giant C. wrote:

bit of sql?

Thanks,
GiantCranes

ids = Model.find(:all, :select => “id”)


Michael W.