How to select an array of values in Rails
I recently wanted to get a list of IDs from rails, but wanted them in an array.
First try is to use :select => 'id' in:
Model.find(:all, :select => 'id')
but that creates a model for each id
In order to get an array of values, you can use select_values:
Model.connection.select_values('select id from models')
This is great, but what if you have a more complex query and you still want to use the query building in Rails finder methods.
You can use construct_finder_sql. This is a private method so it needs to be called via send and you should be cautious about it's availability in future versions of Rails.
The final query then is:
sql = Model.send(:construct_finder_sql, :select => 'id', :conditions => [...])
Model.connection.select_values(sql)
This will be quicker and use less memory because it doesn't create a model object for each id.
I would only use this when pulling fairly large arrays of values, stick to the normal way of doing things for smaller collections.
If you want to get two or three values per 'row', you can use select_rows which will return an array of arrays.
Comments
Have your say