I need to return an array of records (from table Foo) by the number of times they are referenced as a foreign key in either one of two columns of another database table:
id | old_foo_id | new_foo_id
-------------------------------
1 | 1 | 1
2 | 2 | 2
3 | 3 | 3
4 | 1 | 1
5 | 1 | 2
6 | 2 | 4
7 | 4 | 2
8 | 5 | 5
9 | 6 | 6
10 | 7 | 7
For example, using the data above, I need a ActiveRecord (or straight up SQL) query to return a hash ordered by most common foreign keys (counted only once per record if appearing in both old_foo_id
and new_foo_id
) like this:
{"2"=>4, "1"=>3, "4"=>2, "3"=>1, "5"=>1, "6"=>1, "7"=>1}
I have no idea how to do this other than to loop over every Foo object and make a ton of queries - seems very inefficient and time consuming. Thanks so much in advance!
I found a similar question here: Get count of foreign key from multiple tables