On Pluck
January 23, 2012 § Leave a comment
Rails 3.2 has been released and there are a few things in it that I am excited about. I mentioned in a previous post that a few of the things coming in 3.2 were things that I had thought about doing or had already done myself. Turns out I missed one.
ActiveRecord::Relation#pluck
This is the exact same functionality provided by my select-column
gem. It allows you to get an array of column values from the database without having to instantiate an ActiveRecord object for each one. So instead of having to do this:
Post.where(:published => true).collect(&:id)
you can simply do:
Post.where(:published => true).pluck(:id)
The place I see this having a lot of nice applications is in caching. I know that I wrote my gem so that I could use it to speed up some methods that would find appropriate records and then cache the ids for quicker look ups later. I am really excited to do a find and replace of collect for pluck in some of my projects.
Leave a Reply