Search code examples
ruby-on-railsrubyruby-on-rails-5

Remove group_by field from final result rails


I am using rails 5.2.0.

I have a City model in which id is a Primary key and name represents name of city.

I am using group_by to achieve something like this:

Expected Output:

{10571=>"Μorocco Town", 17741=> "S-HERTOGENBOSCH"}

I am trying something like this:

City.all.select('name', 'id').group_by(&:id)

The result I am getting is:

10571=>[#<City id: 10571, name: "Μorocco Town">], 17741=>[#<City id: 17741, name: "S-HERTOGENBOSCH">]}

The key part is correct.
I need to get rid of the id field coming in the hash value and also, a single hash value instead of an array with name as key.

Any suggestions?

Using group_by is not mandatory. Any other inbuilt functions will also work.


Solution

  • Pluck is your friend...

    City.pluck(:id, :name).to_h