Ruby on Rails 4: Pluck results to hash

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)