2013-03-20 112 views
0

我有一个循环中的AR对象的集合,可能会运行很多次,所以我想在每次迭代结束时清空集合。清除ActiveRecord对象集合的最有效方法是什么?

什么是最有效的方法呢?

编辑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 
=> [] 

回答

3

The builtin method

your_array.clear 
+0

是不是只是在做'T = []'好?为什么或者为什么不?其实......只是试过这个,它似乎删除了DB中的记录 - 不是阵列中的记录......这不是我想要做的。 – marcamillion 2013-03-20 09:20:10

+0

更好:释放分配的内存和备用GC工作 – apneadiving 2013-03-20 09:21:08

+0

从数据库中删除预期的行为?对于它的价值,我使用Rails。 – marcamillion 2013-03-20 09:23:44

0

请大家看看Rails doc on associationsclear方法不是Array#clear,它被Rails覆盖。

我只想复制联想的元素,这将确保该协会将偷懒装,喜欢的东西:

tags = w.tags.collect{|t| t} 
tags.clear 
相关问题