It's still not clear what you need. Moreover, using Arel methods chain for such things make them more complex.
If you want to have a list of cities with the sum of amounts from TableA plus modifier from TableB, then it can be obtained with a single SQL-query.
(Assuming you're using PostgreSQL):
SELECT T.city, COALESCE(T.amount, 0) + COALESCE(B.modifier, 0) AS modified_sum
FROM (SELECT city, SUM(amount) AS amount FROM table_a GROUP BY city) T
FULL JOIN table_b B ON B.city = T.city;
http://rextester.com/OSS97422
If you have models TableA and TableB then the query could be converted to a Rails method:
TableA.find_by_sql "SELECT T.city, COALESCE(T.amount, 0) + COALESCE(B.modifier, 0) AS amount
FROM (SELECT city, SUM(amount) AS amount FROM #{TableA.table_name} GROUP BY city) T
FULL JOIN #{TableB.table_name} B ON B.city = T.city"
If your task is to get value for 'Atlanta', then the method call will be:
TableA.find_by_sql ["SELECT T.city, COALESCE(T.amount, 0) + COALESCE(B.modifier, 0) AS amount
FROM (SELECT city, SUM(amount) AS amount FROM #{TableA.table_name} GROUP BY city) T
LEFT JOIN #{TableB.table_name} B ON B.city = T.city
WHERE T.city = :city", { city: 'Atlanta' }]
Please note FULL JOIN
in the first case and LEFT JOIN
in the latter. For 1st query FULL JOIN
provides cities from both tables, A and B. For 2nd call the query looks for 'Atlanta' in TableA.
If your task is different, you can modify these calls as you need.