Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails 4: Pluck results to hash

How can I turn:

Person.all.pluck(:id, :name) 

to

[{id: 1, name: 'joe'}, {id: 2, name: 'martin'}] 

without having to .map every value (since when I add or remove from the .pluck I have to do he same with the .map)

like image 449
Lucas Steffen Avatar asked Mar 15 '16 12:03

Lucas Steffen


People also ask

How do you convert to hash in Ruby?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

How do you pluck in Ruby on Rails?

Use #pluck as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want. Pluck returns an Array of attribute values type-casted to match the plucked column names, if they can be deduced. Plucking an SQL fragment returns String values by default.

What does pluck do Rails?

In Rails, pluck is a shortcut to select one or more attributes without loading the corresponding records just to filter out the selected attributes. It returns an Array of attribute values.

What is TO_H in Ruby?

Ruby | Array to_h() function Array#to_h() : to_h() is a Array class method which returns the result of interpreting ary as an array of [key, value] pairs. Syntax: Array.to_h() Parameter: Array. Return: the result of interpreting ary as an array of [key, value] pairs.


2 Answers

You can map the result:

Person.all.pluck(:id, :name).map { |id, name| {id: id, name: name}} 

As mentioned by @alebian: This is more efficient than

Person.all.as_json(only: [:id, :name]) 

Reasons:

  • pluck only returns the used columns (:id, :name) whereas the other solution returns all columns. Depending on the width of the table (number of columns) this makes quite a difference
  • The pluck solution does not instantiate Person objects, does not need to assign attributes to the models and so on. Instead it just returns an array with one integer and one string.
  • as_json again has more overhead than the simple map as it is a generic implementation to convert a model to a hash
like image 86
Pascal Avatar answered Sep 22 '22 08:09

Pascal


You could simply do this

Person.select(:id,:name).as_json 

You could try this as well

Person.all.as_json(only: [:id, :name]) 
like image 25
Rohit Jangid Avatar answered Sep 18 '22 08:09

Rohit Jangid