【问题标题】:Rails iterate on a collection and return itRails 迭代一个集合并返回它
【发布时间】:2021-05-07 22:20:52
【问题描述】:

我想在 Rails 集合上做一个映射,但我需要结果是一个活动记录集合而不是数组。目前我正在执行以下操作,但这会返回一个数组。

MyModel.all.map do |model|
  model.tap do |m|
    response = fetcher.new.call(m.name)
    m.rating = response[:rating]
  end
end

【问题讨论】:

标签: ruby-on-rails rails-activerecord


【解决方案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

【讨论】:

  • map 是不必要的,您可以改用each 并避免创建一个从未使用过的可能非常大的Array。也不需要tap,因为只需使用model 就可以实现完全相同的结果,因为m === model 产生了该块。
  • 是的。我试图展示快速更改以使其发挥作用。我只是按照你的建议修改了它。
  • 我只是在想也许tap 并不可怕,它应该只是all_records.tap {|ar| ar.each {#...}},但这基本上与之后返回all_records 相同,如您所示。
猜你喜欢
  • 2017-05-02
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2017-04-21
  • 2012-06-16
  • 2018-10-25
相关资源
最近更新 更多