更新时间:2023-01-09 10:41:19
您要做两件事:
仅从数据库中获取您需要的字段,而不是整个用户对象(假设用户中还有其他内容,为简便起见,在此省略)
only fetch fields you need from db, rather than the whole user objects(assuming you have some other stuff in user, which you omitted here for brevity)
Competitor = Struct.new(:html_url, :description, :user)
competitors = []
User.where('watchlists.tags_array' => %w[ruby web framework]).
only(:nickname, :watchlists).each do |u|
u.watchlists.where(:tags_array => %w[ruby web framework]).each do |wl|
competitors << Competitor.new(wl.html_url, wl.description, u.nickname)
end
end
PS:可能您不想在User.all
上使用map
,如果您有大量用户文档,它将需要大量内存.另外,您不是在使用映射的用户,而是自己在competitors
数组中收集结果,因此each
应该可以正常工作.
PS: Probably you do not want to use map
on User.all
, it will require a lot of memory if you have lots of heavy user documents. Also, you are not using the mapped users, but instead collecting results in the competitors
array yourself, so each
should work just fine.