0

I want to do a map on a rails collection but I need the result to be an active record collection instead of array. Currently I am doing the following but this returns an array.

MyModel.all.map do |model|
  model.tap do |m|
    response = fetcher.new.call(m.name)
    m.rating = response[:rating]
  end
end
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Petran
  • 7,677
  • 22
  • 65
  • 104
  • 1
    Similar queston: [Converting an array of objects to ActiveRecord::Relation](https://stackoverflow.com/questions/17331862/converting-an-array-of-objects-to-activerecordrelation) – eux Feb 03 '21 at 16:45
  • 1
    Does this answer your question? [Converting an array of objects to ActiveRecord::Relation](https://stackoverflow.com/questions/17331862/converting-an-array-of-objects-to-activerecordrelation) – Fabian Winkler Feb 03 '21 at 16:56
  • Are you trying to actually update those models? – engineersmnky Feb 03 '21 at 19:11

1 Answers1

1
# 1. get all the records 
all_records = MyModel.all

# 2. Iterate over the collection and modify each model as you are doing
all_records.each do |model|
  response = fetcher.new.call(model.name)
  model.rating = response[:rating]
end

# 3. Return the modified collection
all_records

Amit Patel
  • 15,609
  • 18
  • 68
  • 106
  • 1
    `map` is unnecessary you could use `each` instead and avoid creating a potentially very large `Array` that is never used. Also `tap` is not needed either as the exact same result could be achieved by just using `model` that was yielded to the block since `m === model` – engineersmnky Feb 05 '21 at 00:25
  • True. I tried to show the quick changes to make it work. I just modified it as per your suggestion. – Amit Patel Feb 05 '21 at 08:36
  • I was just thinking maybe `tap` isn't terrible it should just be `all_records.tap {|ar| ar.each {#...}}` but this is essentially identical to just returning `all_records` afterwards as you have shown. – engineersmnky Feb 06 '21 at 00:00