M
M
Mr Freeman2015-07-02 16:30:33
PostgreSQL
Mr Freeman, 2015-07-02 16:30:33

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

and
- !ruby/object:Conversion
attributes:
  count_conversions: 2
  id:  1

And I want to get this
- !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

Still, as I understand it, there is a "manual" way to pass through the first array, then in each iteration of the first array, pass through the second array and with comparisons. But it also seems scary to me. The interpreter will swear.
Please tell me how you would make such a merge in terms of both the ruby ​​language itself with its frame, and in terms of optimizing the script execution speed. If someone does not understand my explanation, I apologize, ask, I will explain. Hope for help. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
thepry, 2015-07-02
@thepry

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 question

Ask a Question

731 491 924 answers to any question