我在一个循环中有一个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
=> []
答案 0 :(得分:3)
your_array.clear
答案 1 :(得分:0)
请查看Rails doc on associations。 clear
方法不是Array#clear
,它被Rails覆盖。
我只是复制关联中的元素,这将确保关联将延迟加载,例如:
tags = w.tags.collect{|t| t}
tags.clear