Ruby on Rails 4: Pluck results to hash

I see three options:

1) pluck plus map:

Person.pluck(:id, :name).map { |p| { id: p[0], name: p[1] } }

2) pluck plus map plus zip and a variable to make it DRY-er:

attrs = %w(id name)
Person.pluck(*attrs).map { |p| attrs.zip(p).to_h }

3) or you might not use pluck at all although this is much less performant:

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

You could simply do this

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

You could try this as well

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

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