Getting close to the database #2 – columns_as_array plugin

Sometimes you just don’t want to instantiate a bunch of ActiveRecord objects for getting some simple information from the database. You might save on memory and it’ll be faster.I made a very simple plugin that enables you to get all the values for one column in a table with a simple class method named according to the column – so for instance you can just say People.first_names and you will get all of them in a hash – key is the id, and value is the first_name.View it here – and install with:script/plugin install http://pennysmalls.com/rails_plugins/column_as_arrayHere’s the README:ColumnAsArray=============This extension allows you to get all the values for a particular column from a table in one hash with a simple call using the column’s name in plural. The resulting hash keys are the ids, and the values are the column values.The idea is that in cases were only one column of data is needed from a table, but all or nearly all items in the table need to be read – perhaps for listing purposes – then we don’t need to instantiate a whole bunch of ActiveRecord objects just for this. This can save a great deal of heap space if there are many columns in a table.Example=======

>> Widget.names=> {7135=>"Big widget", 33=>"Old widget", 100=>"Fast widget">> Thing.updates_ats=> {2865=>"2008-02-04 09:57:55", 2344=>"2008-01-31 10:24:31", 1823=>nil, 260=>nil}

We use singularize to get the column name from the method name, and this works so that column names that are already plural need to have an extra ‘s’:

>> Client.format_choicess=> {7135=>"csv,xml", 33=>"xml", 100=>"csv,xls", 2110=>"csv", 167=>"xml"}
Advertisements

2 thoughts on “Getting close to the database #2 – columns_as_array plugin

  1. there’s also ActiveRecord::Base.connection.select_values("SELECT proam_id FROM state_ograms WHERE state = ‘#{state}’")or what not. Is this different?

  2. This is not particularly technically different from accessing the DB directly – but it certainly looks nice to write:StateOgram.proam_ids..rather than an explicit select string. But we can’t select one column with a condition on another, so your example is not doable with this plugin.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s