Ruby on rails 由于未知OID被视为字符串,ActiveRecord和SQL不返回相同的结果

Ruby on rails 由于未知OID被视为字符串,ActiveRecord和SQL不返回相同的结果,ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,我有个问题。早些时候,我发布了一个与我将要问的问题类似的问题,这个问题已经得到了回答,可以在这里找到,以供参考 这个问题与计算查询结果有关。在这个问题中,我得到的不是相同的计数结果,而是不同的对象结果 以下是ActiveRecord代码: scope :unverified_with_no_associations, -> { find_by_sql("SELECT DISTINCT(accounts.id, accounts.email) FROM accounts WHERE le

我有个问题。早些时候,我发布了一个与我将要问的问题类似的问题,这个问题已经得到了回答,可以在这里找到,以供参考

这个问题与计算查询结果有关。在这个问题中,我得到的不是相同的计数结果,而是不同的对象结果

以下是ActiveRecord代码:

scope :unverified_with_no_associations, -> {
  find_by_sql("SELECT 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)")

这将返回
[#但这看起来我需要深入了解事情的本质,我希望避免这种情况。有人知道这是一个问题吗?

您遇到了这个问题,因为ActiveRecord无法将此行识别为帐户表中的行。AR没有解析sql,也不确定如何处理匿名cortage

如果使用
find\u by\u sql
选择的属性未正确映射到模型,但仍可访问,请尝试:

result.id
result.email
但是你也有两种方法来解决这个问题

首先(这是一个非常粗糙但简单的解决方案),将sql转换为适用于以下范围的Arel

scope :unverified_with_no_associations, -> {
  send(:default_scoped).from(Arel.sql("(SELECT * 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))  
                AS accounts"))
…并调用AR distinct方法:

Account.unverified_with_no_associations.select(:id, :email).distinct
第二个(这是更好的解决方案):

不要直接使用sql。用
Arel
()或
squel
()重写您的作用域

Account.unverified_with_no_associations.select(:id, :email).distinct