I have a conundrum. I am writing a scope on my Account class that finds a bunch of account objects that meet a lengthy condition. Here is my scope:
scope :unverified_with_no_associations, -> {
find_by_sql("SELECT COUNT(DISTINCT(accounts.id, accounts.email)) FROM accounts WHERE level = 0 AND id NOT IN
(SELECT DISTINCT(account_id) FROM verifications) AND id NOT IN
(SELECT DISTINCT(account_id) FROM positions) AND id NOT IN
(SELECT DISTINCT(account_id) FROM edits) AND id NOT IN
(SELECT DISTINCT(account_id) FROM posts) AND id NOT IN
(SELECT DISTINCT(account_id) FROM reviews) AND id NOT IN
(SELECT DISTINCT(sender_id) FROM kudos) AND id NOT IN
(SELECT DISTINCT(account_id) FROM stacks WHERE account_id IS NOT NULL)")
}
When I execute this scope by with Account.unverified_with_no_associations I receive this object back [#<Account:0x007f7fc94d79c0 id: nil>].
However when I connect to the database and execute the sql as is:
SELECT COUNT(DISTINCT(accounts.id, accounts.email)) FROM accounts WHERE level = 0 AND id NOT IN
(SELECT DISTINCT(account_id) FROM verifications) AND id NOT IN
(SELECT DISTINCT(account_id) FROM positions) AND id NOT IN
(SELECT DISTINCT(account_id) FROM edits) AND id NOT IN
(SELECT DISTINCT(account_id) FROM posts) AND id NOT IN
(SELECT DISTINCT(account_id) FROM reviews) AND id NOT IN
(SELECT DISTINCT(sender_id) FROM kudos) AND id NOT IN
(SELECT DISTINCT(account_id) FROM stacks WHERE account_id IS NOT NULL);
I receive the number 221214. Why would it be that I get to differenct results? I've ruled out the possibility of connecting onto different databases. I've checked my .env files and have confirmed that I am in the same database as my application. Does anyone know why I would get such a difference in queries?
------------UPDATE--------
I discovered that find_by_sql does not like the inclusion of COUNT in its argument. When I remove the COUNT() from the sql and later execute a .count method I retrieve the matching number.
However, I still get different results when I use both methods.
What I really need are distinct accounts.id and accounts.email but the methods do not return the same output.
For example, when I execute the sql version I receive an output that looks like this:
row
---------
(1234,[email protected])
but when I use the activerecord version I get this:
[#<Account:0x007fdc9ec104d0 id: nil>]
but with no accompanying email.
----UPDATE #3------
Also on my sql output I get this unknown OID 2249: failed to recognize type of 'row'. It will be treated as String. What does this mean?