使用find_each创建哈希数组

时间:2014-04-16 17:55:58

标签: ruby-on-rails ruby

我正在尝试创建一个哈希数组。我能够使用User.all创建一个,但我不想一次加载所有数据,所以我尝试使用find_each。我是ruby的新手,有人可以指出我做错了吗?

当我使用.all

2.0.0 (main):0 > User.all.as_json.map { |u| {
2.0.0 (main):0 * index: {id: u["user"]["id"]}}}
[{:index=>{:id=>443}},
 {:index=>{:id=>3642}},
 {:index=>{:id=>506}}, ...

当我使用find_each

2.0.0 (main):0 > User.find_each { |u|
2.0.0 (main):0 *   u = u.to_json;
2.0.0 (main):0 *   u = JSON.parse(u);
2.0.0 (main):0 * {index: { id: u["user"]["id"]}}}
  User Load (19.2ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1000
  User Load (18.2ms)  SELECT "users".* FROM "users" WHERE ("users"."id" > 1038) ORDER BY "users"."id" ASC LIMIT 1000
  User Load (21.4ms)  SELECT "users".* FROM "users" WHERE ("users"."id" > 2105) ORDER BY "users"."id" ASC LIMIT 1000
  User Load (14.5ms)  SELECT "users".* FROM "users" WHERE ("users"."id" > 3139) ORDER BY "users"."id" ASC LIMIT 1000
=> nil

1 个答案:

答案 0 :(得分:2)

find_each不返回任何内容,只是将其传递给给定的块。

my_objects = []
User.find_each { |u|
  u = u.to_json
  u = JSON.parse(u)
  my_objects << {index: { id: u["user"]["id"]}}
}
my_objects.to_json

有关查找每项及其使用情况(例如batch_size,e.t.c。)的详细信息,请参阅the docs