我有一个表,其中有几千组 2-3 条几乎相同的记录,它们都共享一个唯一的“id”(不是数据库 ID,而是项目 ID)。也就是说,两到三个记录共享相同的项目 id,大约有 2100 条记录,或约 700 个唯一项目。示例:
{id: 1, product_id:333, is_special:true}, {id:2, product_id:333, is_special:false}, {id:3, product_id:333, is_special:false}, {id:4, product_id:334, is_special:false}...
我想执行一个查询,让我遍历每个集合,修改/删除重复记录,然后移动到下一个集合。
这是我目前拥有的:
task find_averages: :environment do
responses = Response.all
chunked_responses = responses.chunk_while { |a,b| a.result_id == b.result_id}.to_a
chunked_responses.each do |chunk|
if chunk.length < 3
chunk.each do |chunky_response|
chunky_response.flagged = true
chunky_response.save
end
else
chunk.each do |chunky_response|
**manipulate each item in the chunk here**
end
end
end
end
编辑。我在发现 chunk_while
方法后解决了这个问题。我不认为 chunk_while
是这里最有效的方法,但效果很好。我正在关闭这个,但其他任何需要对记录进行分组然后对其进行迭代的人,这应该会有所帮助。
答案 0 :(得分:0)
以下代码应遍历其中一些共享公共值的项目数组,并按公共值对它们进行分组:
responses = Responses.all
chunked_responses = responses.chunk_while { |a,b| a.result_id == b.result_id}.to_a
chunked_responses.each do |chunk|
chunk.each do |chunky_response|
**manipulate each item in the chunk here**
end
end