Img caption: stackoverflow.com

When you select multiple column values using pluck method of ActiveRecord, you usually get an array of arrays. If you want to get an array of hashes with column names as hash keys, you can use this useful Gem called pluck_to_hash.

This gem extends ActiveRecord by adding a new method with the same name as the gem which helps you make sure you are using the right column values.

It can be installed as any other gem. Namely, you need to do to install it is add the following line at your application’s Gemfile:


<span style="font-weight: 400;">gem</span> <span style="font-weight: 400;">'pluck_to_hash'</span>

Then you need to run:


<span style="font-weight: 400;">$ bundle</span>

You can now start to use it.

Let’s say that you want to select the name, city and the number of employees in a factory:


<span style="font-weight: 400;">Factory.pluck_to_hash(:name, :city, :number_of_employess)</span>

In this way, you can now have your results like the following:


<span style="font-weight: 400;"># [{:name=>"Factory A", :city=>"Prishtina", :number_of_employees => 400}, {:name=>"Factory B", :city=>"Prizren", :number_of_employees => 200}]</span>

You can also use the shorter alias pluck_h.

This gem also supports select aliases:


Factory.pluck_to_hash(‘number_of_employees::integer as no_employees’)

You can also use blocks with your plucks:


Factory.pluck_to_hash(:name, :city) {|factory| ...}

For more information regarding this gem, you can visit its GitHub repository.