0

我有一个循环中的 AR 对象集合,可能会运行很多次,所以我想在每次迭代结束时清空集合。

最有效的方法是什么?

编辑 1

这是我使用时发生的情况的示例.clear

1.9.3p392 :039 > t = w.tags
 => [#<Tag id: 32451, name: "c++", num_questions: 180854, created_at: "2013-02-25 07:55:55", updated_at: "2013-02-25 07:55:55">, #<Tag id: 32452, name: "performance", num_questions: 28543, created_at: "2013-02-25 07:55:55", updated_at: "2013-02-25 07:55:55">, #<Tag id: 32453, name: "optimization", num_questions: 10021, created_at: "2013-02-25 07:55:55", updated_at: "2013-02-25 07:55:55">, #<Tag id: 32454, name: "language-agnostic", num_questions: 5942, created_at: "2013-02-25 07:55:55", updated_at: "2013-02-25 07:55:55">, #<Tag id: 32455, name: "branch-prediction", num_questions: 28, created_at: "2013-02-25 07:55:55", updated_at: "2013-02-25 07:55:55">, #<Tag id: 32456, name: "books", num_questions: 2667, created_at: "2013-02-25 07:55:59", updated_at: "2013-02-25 07:55:59">, #<Tag id: 32457, name: "ebook", num_questions: 263, created_at: "2013-02-25 07:55:59", updated_at: "2013-02-25 07:55:59">, #<Tag id: 32458, name: "creative-commons", num_questions: 62, created_at: "2013-02-25 07:55:59", updated_at: "2013-02-25 07:55:59">, #<Tag id: 32459, name: "json", num_questions: 39746, created_at: "2013-02-25 07:56:03", updated_at: "2013-02-25 07:56:03">, #<Tag id: 32460, name: "content-type", num_questions: 874, created_at: "2013-02-25 07:56:03", updated_at: "2013-02-25 07:56:03">] 
1.9.3p392 :040 > t.clear
   (19.0ms)  BEGIN
   (85.2ms)  DELETE FROM "questions_tags" WHERE "questions_tags"."question_id" = 10053 AND "questions_tags"."tag_id" IN (32451, 32452, 32453, 32454, 32455, 32456, 32457, 32458, 32459, 32460)
   (36.5ms)  COMMIT
 => [] 
1.9.3p392 :041 > t
 => [] 
1.9.3p392 :042 > t
 => [] 
1.9.3p392 :043 > w.tags
 => [] 
4

2 回答 2

3

内置方法

 your_array.clear
于 2013-03-20T09:19:04.723 回答
0

请查看有关关联的 Rails 文档。该clear方法不是Array#clear,它被 Rails 覆盖。

我只是复制关联中的元素,这将确保关联将被延迟加载,例如:

tags = w.tags.collect{|t| t}
tags.clear
于 2013-03-20T10:05:04.307 回答