1

I am trying to create an array of hashes. I was able to create one using User.all but I don't want to load all the data at once, so I am trying to use find_each. I am new to ruby can someone point out what I am doing wrong ?

When I use .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}}, ...

When I use 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
3
  • Here's an answer that'll get you most of the way there, might be some messing about with the json. Commented Apr 16, 2014 at 18:08
  • I was curious to know, why you were doing first to_json than JSON.parse?? Commented Apr 16, 2014 at 18:11
  • don't you need to convert it into JSON then parse it to access the data inside ? Commented Apr 16, 2014 at 18:21

1 Answer 1

2

find_each doesn't return anything, it just passes it into the block given.

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

See the docs for more info on find each and it's usage (such as batch_size, e.t.c.).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.