Petran
Petran

Reputation: 8047

Rails iterate on a collection and return it

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

Upvotes: 0

Views: 636

Answers (1)

Amit Patel
Amit Patel

Reputation: 15985

# 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

Upvotes: 1

Related Questions