Arnold Roa
Arnold Roa

Reputation: 7708

Rails how to build a hash from results

I have a table on Db with two fields: group and text

I want to retrieve all records and convert into an hash grouped by the group field, and containing an array of all texts, something like this:

{
    'group_1': ['text1','text2',...]
    'group_2': ['text1','text2',...]
    'group_3': ['text1','text2',...]
}

I acomplish it partially with this

MyModel.all.group_by(&:group)

but it returns an array with all the full AR object, i just want an array of all the text strings

I was trying with map but I can figure out how to do this without using each

Any idea?

Upvotes: 1

Views: 47

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

Try the following:

MyModel.all.select([:text, :group]).group_by(&:group)

If you wanted to use an iterator (ex: each/map), here is how you would do it:

grouped_models = MyModel.all.group_by(&:group)
grouped_models.map do |group, models|
  grouped_models[group] = models.map(&:text)
end

grouped_models
# => { 'group_1' => ['text1', 'text2'], 'group_2' => ['text'] }

Upvotes: 1

Related Questions