Z
Z
Zaur Ashurbekov2014-09-03 18:34:15
Ruby on Rails
Zaur Ashurbekov, 2014-09-03 18:34:15

Why can't ActiveRecord work as an array?

Hello Habr!
There is a code that passes some hash to gon:

gon.select_options = Product.all.to_a.inject({}) do |hash, product|
      hash[product.id] = product.materials.to_a.inject({}) do
            |materials_hash, material| materials_hash[material.id] = get_material_data_hash(material)
      end
end

But in the end, this hash is empty, although there are records in the database. What could be the problem?
UPD. Here is the query log, which seems to say that there are values
ActiveRecord::SchemaMigration Load (0.3ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by AdminPanelController#materials_panel as HTML
  Product Load (0.1ms)  SELECT "products".* FROM "products"
  Material Load (0.6ms)  SELECT "materials".* FROM "materials" INNER JOIN "materials_products" ON "materials"."id" = "materials_products"."material_id" WHERE "materials_products"."product_id" = ?  
  Material Load (0.3ms)  SELECT "materials".* FROM "materials" INNER JOIN "materials_products" ON "materials"."id" = "materials_products"."material_id" WHERE "materials_products"."product_id" = ?  
  Material Load (0.2ms)  SELECT "materials".* FROM "materials" INNER JOIN "materials_products" ON "materials"."id" = "materials_products"."material_id" WHERE "materials_products"."product_id" = ?  

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2014-09-04
@zaurius

The problem is that the block in the inject method must return a new value for the first parameter, i.e. in your case the same Hash instance into which you write the result
. Here is the inject variant that should work

gon.select_options = Product.all.to_a.inject({}) do |hash, product|
      hash[product.id] = product.materials.to_a.inject({}) do |materials_hash, material|
            materials_hash[material.id] = get_material_data_hash(material)
            materials_hash
      end
      hash
end

Or use each_with_object instead of inject

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question