Answer the question
In order to leave comments, you need to log in
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
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question