I have a table objects like this:
id | date | other_ids
===|============|=========
1 | 1489495210 | {3}
2 | 1489495520 | {}
3 | 1489495560 | {5,9}
4 | 1489496588 | {4}
5 | 1489496948 | {}
6 | 1489497022 | {1,3,8}
7 | 1489497035 | {3}
8 | 1489497318 | {2,4}
9 | 1489507260 | {}
I am attempting to write a query to output a list of Object ids with the latest date for each of a specified array of other_ids. For example:
specified_other_ids = [1, 2, 4]
ids = //...
# => ids = [6, 8]
# Note that the max date occurs at id 8 for other_id 2 AND 4, so no duplicates returned
My understanding is that UNNEST is used to break the other_ids arrays into rows, and then I should be able to use DISTINCT ON with the un-nested rows. So this is my attempt:
ids = Object.from("objects, UNNEST(objects.other_ids) AS other_id")
.where("other_id IN (?)", specified_other_ids)
.order("other_id, date DESC")
.pluck("DISTINCT ON(other_id) id")
This works as I would expect when running in development, staging and production consoles. However, when running rspec in the test environment (via Codeship) every test running that code fails when that query is run, with the following error:
ActiveRecord::StatementInvalid: PG::InvalidColumnReference: ERROR: function expression in FROM cannot refer to other relations of same query level
So my first thought is that Postgres is somehow configured differently in the test environment, though I also have a sense that I'm somehow not using the Postgres UNNEST function properly. Where should I start looking for a solution to this?
P.S. I'm not an experienced Rails/SQL dev, so detailed explanations would be much appreciated to help me learn!