On Selecting A Single Column
July 9, 2011 § 1 Comment
Many times when we are selecting a rows out of the database we just want a single column and have no need for the entire object. There are a number of ways to accomplish this with ActiveRecord. One can get all the records from the database and then collect the attribute needed:
Posts.where(:status => 'published').collect(&:id) => [ 1, 5, 8, 10 ]
This has the benefit of being able to us any overwritten accessors, but has a lot of overhead associated with generating the objects. Another way to do it is to go directly to the database:
ActiveRecord::Base.connection.select_values("SELECT id FROM posts WHERE status = 'published'") => [ 1, 5, 8, 10 ]
This is much faster, but requires one to use the direct connection to the database and have the SQL literal prepared. Not particularly user friendly even if you can get the SQL literal using the to_sql:
ActiveRecord::Base.connection.select_values(Posts.where(:status => 'published').select(:id).to_sql) => [ 1, 5, 8, 10 ]
Wouldn’t it be nicer if you could just do the following:
Post.where(:status => 'published').select_column(:id) => [ 1, 5, 8, 10 ]
The select-column gem provides the above functionality above. You can you it in your Rails 3 app or checkout the source code over on github.
select_column accepts a single optional argument. This is the column that you want to have returned in an array. The returned column can also be specified using the select query method.
If neither a select nor an argument is given,
:id is assumed to be the column to be returned. If multiple select query methods are present, the first one defined will be the column returned.
# selects an array of ids Post.select_column # selects an array of titles Post.select_column(:title) # selects an array of ids Post.where(:status => 'published').select_column # selects an array of titles Post.where(:status => 'published').select_column(:title) # selects an array of titles Post.select(:title).where(:status => 'published').select_column
Update (Jan 21, 2012): It’s like they keep looking at my gems and integrating them into Rails. As of Rails 3.2 this gem’s functionality has been replicated by
ActiveRecord::Relation#pluck. Check it out in the release notes.