Search code examples
rubyruby-on-rails-4

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)


Solution

  • You could simply do this

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

    You could try this as well

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