(P)Lucky me!

While working on my CLI project this past week, I constantly found myself looking to grab certain parts of records, and as a consequence, had to write extra lines of code to grab needed attributes from those objects once they were created. Over time, this adds up…If only there was a better way!

Explosion, thankfully, not relevant.

Luckily, I stumbled upon the the handy pluck ActiveRecord method! Pluck allows the developer to grab whatever column they please, and have it returned in an array, without having to load the entire record. Sounds great to me!

Image courtesy of https://collectiveidea.com/blog/archives/2015/05/29/how-to-pluck-like-a-rails-pro

As you can see, pluck is passed a symbol of the column name as an argument…what’s cooler than one column name?…

It’s Christmas in August!

MORE THAN ONE. With pluck, you can actually pass more than one key to the argument, to get a nested array with the values of said keys! Much quicker than a normal Active Record select statement!

Pluck can also be chained to the returns of other Active Record methods, and is extremely handy for some quick procuring of column values. This comes in handy when you may want to grab values from different tables, as you can easily grab the values you need by proceeding the pluck with a join statement. One other handy use for pluck is to pass it a string of raw SQL either via string or the fancier heredoc to craft more specific SQL queries!

In summary, pluck can alleviate SOME of the headache that comes from grabbing column information of a database. If you ever need to grab some quick column information, but don’t need to instantiate a whole object, pluck may be the ActiveRecord method for you!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.