Answer the question
In order to leave comments, you need to log in
How to recursively merge two objects by index?
That is, what is the situation - there are two aggregated queries for different tables for the same field (this field is in both the first and second tables, for example, we group goods and orders by user_id, while using SUM, COUNT, etc.).
The way out is this - we first aggregate the goods by user_id, then we go through .each() by records and pull out orders according to the WHERE condition user_id=user.id and push it into the array there. But this will be terrible for a large number of goods, since the number of requests = number of goods + 1, well, that is, a request in a cycle is completely "Nubian".
In PHP, I did like - two groupings with the same index (user_id), and then array_replace_recursive did its job perfectly. How about here? Here is the data AR returns me
- !ruby/object:Track
attributes:
clicks: 7
hosts: 3
campaign_id: 4
id: 1
- !ruby/object:Track
attributes:
clicks:
hosts: 1
campaign_id: 2
id: 2
- !ruby/object:Conversion
attributes:
count_conversions: 2
id: 1
- !ruby/object:Track
attributes:
clicks: 7
count_conversions: 2 // вот эти данные "вмержились" по индексу id=1
hosts: 3
campaign_id: 4
id: 1
- !ruby/object:Track
attributes:
clicks:
hosts: 1
campaign_id: 2
id: 2
Answer the question
In order to leave comments, you need to log in
I didn't fully understand the question, but instead:
You can get an array from user_id and make one request.
You can do this:
products_hash = Products.bla-bla-bla.group_by(&:user_id)
orders_hash = Orders.bla-bla-bla.group_by(&:user_id)
products_hash.merge(orders_hash){ |key, oldval, newval| Тут ваш код, который правильно сопоставит данные из двух массивов }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question