Img caption:

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:

gem 'pluck_to_hash'

Then you need to run:

$ bundle

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:

Factory.pluck_to_hash(:name, :city, :number_of_employess)

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

# [{:name=>"Factory A", :city=>"Prishtina", :number_of_employees => 400}, {:name=>"Factory B", :city=>"Prizren", :number_of_employees => 200}]

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.